我有以下内容:
<name-view data-topic='id'></name-view>
import 'dart:html';
class NameView implements AfterViewInit
{
String topic;
void ngAfterViewInit( ) {
// datset is not reference below - works in polymer-1.x attached() method
topic = this.datset['topic'];
}
}
但是,ngAfterViewInit中的代码不起作用。 如何在angular2?
中检索data-topic属性答案 0 :(得分:0)
我无法让@Input('data-topic')
工作,但其他方式正常工作
@Component(
selector: 'app-element',
template: '''
<h1>app-element</h1>
<name-view data-topic='id' topic='topicid'></name-view>
''',
directives: const [NameView])
class AppElement {}
@Component(
selector: 'name-view',
template: '''
<h1>test-element</h1>
<div>data-topic: {{topic}}</div>
<div>topic: {{topic2}}</div>
<div>topicFromRef: {{topicFromRef}}</div>
''')
class NameView implements OnInit {
@Input('data-topic')
String topic;
@Input('topic')
String topic2;
String topicFromRef;
ElementRef _elementRef;
TestElement(this._elementRef);
void ngOnInit() {
topicFromRef = (_elementRef.nativeElement as Element).dataset['topic'];
}
}
不鼓励使用ElementRef
,因为这会阻止在WebWorker中或在服务器渲染上运行代码。