![](/img/trans.png)
[英]Call the component dynamically angular2, attaching customElement to DOM onClick
[英]Call Angular web component method (CustomElement)
我有这两个例子:
示例 1:
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
options:any = {isOpen: false };
logOptions() {
console.log(this.options);
}
}
示例 2:
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
options:any = {isOpen: false };
@Input() logOptions() {
console.log(this.options);
}
}
在 html 中:
<app-root></app-root>
<script>
document.querySelector('app-root').logOptions();
</script>
在示例 1 中返回错误: document.querySelector(...).logOptions is not a function
在示例 2 中返回: undefined
有没有人有任何想法?
有点晚了,但如果你仍然需要这个,有几种方法可以让它工作。
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
// @Input() << see comments below
options: any = {isOpen: false };
// This will NOT be available outside the component, in plain JS
logOptions() {
console.log(this.options);
}
// This will work ONLY if options is @Input()
@Input()
logOptions2() {
console.log(this.options);
}
// This property will always provide correct data
// Ideally a getter should not be @Input() though
@Input()
get logOptions3() {
return this.options;
}
}
您可以使用普通的JavaScript
代码访问它们
const logComponentOptions = () => {
const el = document.querySelector('app-root');
// el.logOptions(); << Error
el.logOptions2(); // works ONLY if options is @Input()
console.log(el.logOptions3); // WORKS
console.log(el.options); // if options is @Input()
}
logOptions3
属性总是可以用来从普通的javaScript
代码中获取options
。 但语义上不正确(作为@Input()
的getter
)logOptions()
方法不能从外部访问,因为它没有标记为@Input()
logOptions2()
方法是可访问的,但只能打印正确的值,如果options
也被标记为@Input()
options
属性标记为@Input()
,则可以直接访问它本身,而不是将其包装在另一个方法中@Input() options = false
,您也可以将其作为HTML
的简单属性访问<app-root options="false"></app-root>
如果您想将数据传递到组件中,您可以简单地使用@Input
公开一个setter
属性。 然后您可以使用JavaScript
从组件外部设置值
@Input()
public set myData(value: MyDataType) {
// validation & logic if any
this._myData = value;
}
// Then in JavaScript
const el = document.querySelector('app-root');
el.myData = {a: 10, b: true, c: 'my data object' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.