无法获取未定义或null引用角度为2的属性“nativeElement”

时间:2017-03-05 09:42:42

标签: angular

我试图在单击其中一个链接时隐藏其他链接,我尝试在组件中使用“Viewchild”来访问锚标记的name属性。请在组件中找到以下代码。

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访问元素的上述代码有什么问题,还有其他方法可以访问anchor标记的name属性值吗?

我尝试按照以下链接进行修复,但没有解决问题的好运

@viewChild not working - cannot read property nativeElement of undefined

1 个答案:

答案 0 :(得分:2)

我可以看到您的代码有些问题。对于初学者,您应该在锚标记中使用#name="first"而不是let name="first"。但是,您有多个具有相同名称的ViewChildren,但它仍然无效。

访问原始DOM元素可能不是这里的答案。我宁愿做这样的事情:

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="isSelected('first')" (click)="setState('first')">First</a> |
               <a routerLink="Second" *ngIf="isSelected('second')" (click)="setState('second')">Second</a> |
               <a routerLink="Third" *ngIf="isSelected('third')" (click)="setState('third')">Third</a> |
               <a routerLink="Fourth" *ngIf="isSelected('fourth')" (click)="setState('fourth')">Fourth</a> 
</div>
<br/>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent {
    private selectedLink: string;

    setState(e: string): void {
        this.selectedLink = e;
    }

    isSelected(name: string): boolean {
        if (!this.selectedLink) { // if no link is selected, always return true so everything is shown
            return true;
        }

        return (this.selectedLink === name); // if current link is selected, return true, else return false
    }
}