我试图隐藏其他链接,当单击其中一个链接时,我已尝试在组件中使用“Viewchild”来访问名称属性的锚标签。请在组件中找到下面的代码。无法获取未定义的属性'nativeElement'或空参考角度2
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;
}
}
}
什么是错上面的代码访问的元素与viewchild,有没有在那里我可以访问定位标记的name属性值的任何其他方式?
我试着跟随下面的链接来解决,但在解决问题
@viewChild not working - cannot read property nativeElement of undefined
你需要通过id引用..其中是你的html中设置的id? –
另外,setState在哪里调用?确保只在viewInit之后调用它。 – EluciusFTW
为什么你首先需要访问本地元素?最有可能比访问dom元素更好的解决方案。你想达到什么目的? –