I am trying to hide the other links when one of the link is clicked, I have tried using "Viewchild" in the component to get access to the name attribute of the anchor tag. Please find the below code in the component.
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular App</h1>
<div style="float:right;">
<a routerLink="First" *ngIf="!isOn" (click)="setState(first)" let name="first">First</a> |
<a routerLink="Second" *ngIf="!isOn" (click)="setState(second)" let name="second">Second</a> |
<a routerLink="Third" *ngIf="!isOn" (click)="setState(third)" let name="third">Third</a> |
<a routerLink="Fourth" *ngIf="!isOn" (click)="setState(fourth)" let name="fourth">Fourth</a>
</div>
<br/>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent {
private isOn: boolean = false;
private trst: string;
@ViewChild('name') input3: ElementRef;
ngAfterViewInit() {
console.log(this.input3.nativeElement);
}
setState(e: any): void {
var native = this.input3.nativeElement; //throws error here
var myattr = native.getAttribute("input3");
alert("my attribute value is from click : " + myattr);
this.trst = this.input3.nativeElement.value;
alert(this.trst);
alert(e);
if (this.trst == e)
{
this.isOn = false;
}
else
{
this.isOn = true;
}
}
}
What is wrong with above code accessing the element with viewchild, is there any other way where I can access the name attribute value of anchor tag?
I tried following the below link to fix , but had no luck in resolving the issue
@viewChild not working - cannot read property nativeElement of undefined