use*_*980 9 angular2-directives angular
我有一个附加元素的Angular 1.x指令.简而言之:
app.directive('mydirective', function() {
template: '<ng-transclude></ng-transclude>',
link: function(el) {
var child = angular.element("<div/>");
el.append(child);
}
Run Code Online (Sandbox Code Playgroud)
我可以将此指令迁移到Angular 2,如下所示:
@Directive({
selector: '[mydirective']
})
export class MyDirective implements OnInit {
constructor(private elementRef: ElementRef) { }
ngOnit() {
var child = angular.element("<div/>");
this.elementRef.nativeElement.append(child);
}
}
Run Code Online (Sandbox Code Playgroud)
令我不安的是nativeElement官方文件中的这句话:
当需要直接访问DOM时,使用此API作为最后一个资源.
我的问题是 - 我怎样才能将此指令正确地迁移到Angular 2?我唯一的要求是动态构建一个元素,并使用该指令将其附加到元素.
Max*_*kyi 14
使用RendererAngular提供的操作DOM:
import { DOCUMENT } from '@angular/common';
export class MyDirective implements OnInit {
constructor(private elementRef: ElementRef, private renderer: Renderer2, @Inject(DOCUMENT) private document) { }
ngOnInit() {
const child = document.createElement('div');
this.renderer.appendChild(this.elementRef.nativeElement, child);
}
}
Run Code Online (Sandbox Code Playgroud)
这不依赖于本机DOM API appendChild(),因此在某种程度上它是一种独立于平台的方法.
| 归档时间: |
|
| 查看次数: |
21431 次 |
| 最近记录: |