joe*_*ter 31 dom angular2-template angular2-components angular
我有一个Angular 2组件,我想<div id ="myId">
通过它的id 检索一个元素div
.我尝试:document.getElementById("myId")
在我的组件(TypeScript)中,但我收到一个错误:"找不到名称文档".我看到在其他帖子中我们可以使用@ViewChild做类似的事情,但是我看不出我们如何使用div,任何想法?
Jay*_*ase 62
您可以通过添加TemplateRef将@ViewChild与div一起使用.
模板
<div id ="myId" #myId>
Run Code Online (Sandbox Code Playgroud)
零件
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('myId') myId: ElementRef;
constructor() {
}
ngAfterViewInit() {
console.log(this.myId.nativeElement);
}
}
Run Code Online (Sandbox Code Playgroud)
这篇由Kara Erickson撰写的博客文章非常适合熟悉Angular方法来做这样的事情.
Sei*_*vic 13
将模板引用变量添加到您需要访问的元素:
<div #myDiv></div>
Run Code Online (Sandbox Code Playgroud)
在组件中:
class MyComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
constructor() {}
ngAfterViewInit() {
console.log(this.myDiv);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
60338 次 |
最近记录: |