【发布时间】:2018-06-11 15:57:38
【问题描述】:
我正在尝试将 Angular 组件用作自定义元素,以便我可以动态地将其添加到 DOM 并自动引导,但我还需要将此组件作为另一个组件模板的一部分。
我已将 Description 组件注册为自定义元素,并且只要我将以下内容添加到 dom,它就会正确引导:
<app-description text="Some description text..."></app-description>
但是,如果我想将该组件用作 Header 组件模板的一部分(该模板具有正确设置的属性 descriptionText),则不会显示任何描述。我是这样使用它的:
<app-description text="{{descriptionText}}"></app-description>
我也试过了:
<app-description [text]="descriptionText"></app-description>
和
<app-description text="descriptionText"></app-description>
但无论如何我都没有得到预期的结果。
所以,我的问题是: 有没有办法将 Angular 组件定义为自定义元素,并且还能够将其包含在任何 Angular 组件的模板中?
编辑: 我在 Header 和 Description 组件的 ngOnInit 方法中放置了一个 console.log() ,我在控制台中打印了这个:
似乎组件被初始化了两次,第二次'text'设置为未定义?
描述组件:
@Component({
selector: 'app-description',
templateUrl: './description.component.html',
styleUrls: ['./description.component.css']
})
export class DescriptionComponent implements OnInit {
@Input() text: String;
constructor() {}
ngOnInit() {
console.log('text:', this.text)
}
}
描述模板:
<div class="description">
<h3>{{ text }}</h3>
</div>
头组件:
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
@Input() title: String;
@Input() subtitle: String;
@Input() descriptionText: String;
constructor() {}
ngOnInit() {
console.log('descriptionText:', this.descriptionText)
}
}
页眉模板:
<div class="header flex-container">
<h1>{{ title }}</h1>
<h2>{{ subtitle }}</h2>
{{descriptionText}} <!-- shown correctly! -->
<app-description text="{{descriptionText}}"></app-description>
</div>
模块:
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
DescriptionComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [],
entryComponents: [
AppComponent,
HeaderComponent,
DescriptionComponent
],
schemas : [
CUSTOM_ELEMENTS_SCHEMA
]
})
export class AppModule {
constructor(private injector: Injector) {
this.registerCustomElements();
}
ngDoBootstrap() {}
registerCustomElements() {
const HeaderElement = createCustomElement(HeaderComponent, {injector: this.injector});
customElements.define('app-header', HeaderElement);
const DescriptionElement = createCustomElement(DescriptionComponent, {injector: this.injector});
customElements.define('app-description', DescriptionElement);
}
}
我正在使用 Angular 6 中提供的 Angular 自定义元素
谢谢!
【问题讨论】:
-
所有你应该工作的东西(除了最后一个;那是文字“descriptionText”而不是变量。你有任何控制台错误吗?
-
感谢您的回答,布拉德利。我没有收到任何控制台错误,但我看到的是属性“文本”没有被传递给组件。
-
@BradleyDotNET 请查看我的编辑,我添加了更多信息。谢谢!
-
两次初始化很奇怪;您能否在 GitHub 上发布更多代码甚至链接到工作示例?
-
@BradleyDotNET 我在编辑中添加了一些代码!
标签: angular web-component angular6 custom-element