Vis*_*ati 10 typescript angular2-components angular angular5
我们如何在Angular(版本2.x及更高版本)中获取DOM元素?addClass,removeClass等基本函数在打字稿中是不可用的,那么我们如何在角度组件中进行这些DOM操作呢?请建议是否有.TIA
ome*_*per 10
您可以通过以下方式使用ViewChild装饰器来访问DOM元素:
@Component({
....
templateUrl: 'mytemplate.html'
})
export class MyComponent{
@ViewChild('selector') private someName;
constructor() {
//this is your dom
//this.someName.nativeElement
}
}
Run Code Online (Sandbox Code Playgroud)
在你的模板类中,你必须指定谁是那个选择器
<div #selector> </div>
Run Code Online (Sandbox Code Playgroud)
或者您可以使用ElementRef类
import {Component, AfterViewInit,ElementRef} from "@angular/core";
export class MyComponent implements AfterViewInit {
constructor(protected elementRef: ElementRef) {
}
ngAfterViewInit() {
//you can reach your dom element by using
//this.elementRef.nativeElement
}
}
Run Code Online (Sandbox Code Playgroud)
你可以自由地使用像Jquery这样的第三方库来获取addClass,在typescript中使用removeClass.
诸如addClass,removeClass等基本函数在typescript中是不可用的
他们是可用的.可以在JS中完成的所有操作都可以在TypeScript中完成.您也可以使用jQuery,但不鼓励与Angular2一起使用
一些解释如何获取元素angular 2/typescript的引用 :获取模板中的元素
话虽这么说,在Angular2你应该避免势在必行修改DOM,而是使用具有类似的结构指令结合*ngFor,*ngIf...,结合样[class.class-name']="true"或指令一样ngClass.
有关详细信息,请参阅https://angular.io/docs/ts/latest/guide/
| 归档时间: |
|
| 查看次数: |
22302 次 |
| 最近记录: |