angular4 viewchild没有在dom元素上工作

时间:2017-07-08 22:35:23

标签: javascript angular

我想知道如何从组件模板中获取dom元素:

组件

export class JokeListComponent implements OnInit, AfterViewInit {


  jokes: Joke[];
  constructor() { }
  @ViewChild('.myclass') el:  ElementRef;

  ngOnInit() {

    this.jokes = [
      new Joke('joke1', 'content1'),
      new Joke('Joke2', 'content2'),
      new Joke(),
    ];

  }

  ngAfterViewInit(): void {
    console.log(this.el);
  }
}

查看

<div class="card">
    <div class="card-block">
        <h4 class="card-title"> New Joke Form </h4>

        <div class="myclass">

        </div>

        <div class="form-group">
            <label for="jokeHeader">Joke Header</label>
            <input type="text" id="jokeHeader" class="form-control" placeholder="Joke Head" #jokeHead>
        </div>

        <div class="form-group">
            <label for="jokeContent">Joke Header</label>
            <input type="text" id="jokeContent" class="form-control" placeholder="Joke Content" #jokeContent>
        </div>

        <button class="btn btn-primary" (click)="addJoke(jokeHead.value, jokeContent.value)"> Validate </button>

    </div>
</div>

<hr>

<joke *ngFor="let joke of jokes" [joke]="joke" (deleteEvt)="deleteJoke($event)"></joke>

问题是this.el总是未定义,我不知道为什么。

PS:我正在使用最新版本的angular 4

1 个答案:

答案 0 :(得分:3)

你不能使用@ViewChild的类名,你需要一个局部变量:

@Component({
      template: `
      <div><span #myVar>xxx</span><div>`
    })
    class MyComponent {
      @ViewChild('myVar') myVar:ElementRef;

      ngAfterViewInit() {
        console.log(this.myVar.nativeElement);
      }
    }