为什么在尝试通过id获取元素时会得到null?

时间:2018-08-24 22:54:11

标签: angular angular5

加载模板时,我试图修改页面中的元素:

ngAfterContentInit() {
    var oldParent = document.getElementById('card-list-wrapper');
    console.log(oldParent);
    document.body.innerHTML += oldParent;
    oldParent.innerHTML = '';
  }

模板:

<div *ngIf="dataLoaded2" id="card-list-wrapper"></div>

但是我得到console.log(oldParent);为空,为什么?

1 个答案:

答案 0 :(得分:2)

最好避免在打字稿文件中使用普通JS:

<div *ngIf="dataLoaded2" id="card-list-wrapper" #card></div>

并在ts文件中:

export class elementComponent implements OnInit {

  @ViewChild("card", {read: ElementRef}) card: ElementRef;

    constructor(private elementRef: ElementRef) {}

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

}