I bring data from the server to the client And in the model I have a url I want to navigate with the url to websites
The problem is, when I click on the link, it redirects me to the page and does not direct me to the site: enter image description here
For example:
"id": 1,
"name": "Google",
"url": "www.google.com",
By click a link I want to navigate to Google
Model:
export default class Site{
id: number = -1;
name: string = '';
url: string = '';
}
components.ts:
export class AppComponent implements OnInit{
sites: Site[] = [];
constructor(private siteService:SiteService, private router: Router) { }
ngOnInit(): void {
this.GetSites();
}
GetSites() {
this.siteService.GetSites()
.subscribe((sites) => {
this.sites = sites;
});
}
}
HTML:
<div *ngFor="let item of sites; let i = index">
<div>Id: {{item.id}}</div>
<div>Name: {{item.name}}</div>
<a href="item.url">{{item.url}}</a>
</div>
CodePudding user response:
You are currently passing the plain string "item.url" as the URL to the anchor tag. If you want to pass the attribute of your JSON object to the anchor tag, you should include brackets ([]
) in order to bind your object attribute to it:
<a [href]="item.url">{{item.url}}</a>
Edit after feedback in comments
You should also include the protocol in your url
attribute, e.g. changing
"url": "www.google.com",
to
"url": "http://www.google.com",