リンクの1つがクリックされたときに他のリンクを非表示にしようとしていますが、コンポーネントで「Viewchild」を使用して名前属性アンカータグのコンポーネントの下のコードを見つけてください。 viewchildで要素にアクセスする上記のコードと間違っている何未定義またはnull参照角度のプロパティ '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;
}
}
}
、私はアンカータグのname属性の値にアクセスすることができ、他の方法はありますか?
私は修正するには、以下のリンクをたどってみましたが、問題に
@viewChild not working - cannot read property nativeElement of undefined
あなたはidで参照する必要があります。あなたのHTMLにはどのようなIDが設定されていますか? –
また、setStateはどこに呼び出されますか? viewInitの後でのみ呼び出されることを確認してください。 – EluciusFTW
最初にネイティブエレメントにアクセスする必要があるのはなぜですか?おそらくDOM要素にアクセスするよりはるかに良い解決策があります。あなたは何を達成しようとしていますか? –