24
比方說,最好的辦法我已經在角2Angular2:什麼是得到一個模板元素的參考
@Component ({
directives: [Timeline, VideoPlayer],
template: `<div>
<span id="myId"></span>
<videoplayer [mode]="mode"></videoplayer>
<timeline [mode]="mode"></timeline>
</div>`,
})
export class VideoEditor {
}
這樣的組件怎樣才能從模板的元素的引用?例如,我如何獲得對<span>
的參考?
我發現兩種方法迄今:
1)獲取使用參考ElementRef
export class VideoEditor {
constructor (private el: ElementRef) {
el.nativeElement.getElementsBy.....;
}
}
2)使用ViewChild
export class VideoEditor {
@ViewChild(Timeline) timeline: Timeline;
ngAfterViewInit() {
this.timeline;
}
}
1)我不喜歡第一種方法是我需要做類似getElementsBy...
的功能。
2)關於第二個,我不知道如何獲得一個HTML元素的訪問權限,我只能訪問另一個子組件。如果我有更多的同一類型的子組件呢?
3)本地模板變量只能在模板中使用,對嗎?
在Angular 2中獲取對模板的引用的最佳方式是什麼? 我想有東西等反應具有 https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
<input ref="myInput" />
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
感謝您的回答,請您詳細介紹一下如何使用綁定進行操作?你是什麼意思? –
這取決於您實際想要對標記進行的引用。對於綁定,我的意思是''。 –
假設我想關注''。最好的辦法是做'@ViewChild('keywordInput')keywordInput;'然後'this.keywordInput.nativeElement.focus();'我是對嗎?對不起,這有點超出了我的問題範圍。 –