假设我在Angular 2中有一个这样的组件.
@Component ({
directives: [Timeline, VideoPlayer],
template: `<div>
<span id="myId"></span>
<videoplayer [mode]="mode"></videoplayer>
<timeline [mode]="mode"></timeline>
</div>`,
})
export class VideoEditor {
}
Run Code Online (Sandbox Code Playgroud)
如何从模板中获取对元素的引用?例如,我如何获得对<span>?的引用?
到目前为止我找到了两种方法:
1)使用ElementRef获取参考
export class VideoEditor {
constructor (private el: ElementRef) {
el.nativeElement.getElementsBy.....;
}
}
Run Code Online (Sandbox Code Playgroud)
2)使用ViewChild
export class VideoEditor {
@ViewChild(Timeline) timeline: Timeline;
ngAfterViewInit () {
this.timeline;
}
}
Run Code Online (Sandbox Code Playgroud)
3)使用本地模板变量
1)我不喜欢第一种方法是我需要做类似getElementsBy...功能.
2)关于第二个,我不知道如何访问HTML元素,我只能访问另一个子组件.如果我有更多相同类型的子组件怎么办?
3)本地模板变量只能在模板中使用,对吗?
在Angular 2中获取模板引用的最佳方法是什么?我想要像React这样的东西有 https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
<input ref="myInput" />
Run Code Online (Sandbox Code Playgroud)
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = …Run Code Online (Sandbox Code Playgroud) 我正在使用Angular2并从官方网站下载了package.json.当我试图在@Component装饰器中使用"指令"时,我收到此错误.
我附上了我的代码错误:
[ts]
Argument of type '{ selector: string; template: string; directives: string;
}' is not assignable to parameter of type 'ComponentMetadataType'.
Object literal may only specific known properties, and 'directives' does not
exist in type 'ComponentMetadataType'.
(property) directives: string
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import { Component } from '@angular/core';
import { PeopleListComponent } from './people-list/people-list.component';
@Component({
selector: 'my-app',
template: '<h1>{{ title }}</h1>',
directives: '' //ERROR //NOT ABLE TO RECOGNIZE
})
export class AppComponent {
title = "My title";
}
Run Code Online (Sandbox Code Playgroud)
这是我的package.json:
{
"name": …Run Code Online (Sandbox Code Playgroud)