Javascript 使用Angular和typescript以编程方式将按钮添加到模板
我正在尝试将组件(按钮)添加到角度模板中,但它无法按预期工作: basicButton.component.htmlJavascript 使用Angular和typescript以编程方式将按钮添加到模板,javascript,angular,typescript,components,Javascript,Angular,Typescript,Components,我正在尝试将组件(按钮)添加到角度模板中,但它无法按预期工作: basicButton.component.html <button type="button" (click)="changeName()">{{label}}</button> form.component.ts import { Component } from "@angular/core"; @Component({ selector: "basic-button", template
<button type="button" (click)="changeName()">{{label}}</button>
form.component.ts
import { Component } from "@angular/core";
@Component({
selector: "basic-button",
templateUrl: "./basicButton.component.html"
})
export class BasicButtonComponent {
label: string = "default";
public changeLabel(l: string) {
this.label = l;
}
}
import { Component, OnInit } from "@angular/core";
import { BasicButtonComponent } from "./basicButton.component";
@Component({
selector: "form-component",
template: `<h1>Hello {{name}}</h1>
<basic-button></basic-button>
{{button2}}`
})
export class FormComponent implements OnInit {
name = "Mario";
button2: BasicButtonComponent;
setButtonText(t: string) {
this.button2.changeLabel(t);
}
ngOnInit() {
this.button2 = new BasicButtonComponent();
this.setButtonText("test1");
}
}
从“@angular/core”导入{Component,OnInit};
从“/basicButton.component”导入{BasicButtonComponent};
@组成部分({
选择器:“表单组件”,
模板:`Hello{{name}}
{{button2}}`
})
导出类FormComponent实现OnInit{
name=“马里奥”;
按钮2:基本按钮组件;
setButtonText(t:字符串){
此.按钮2.更改标签(t);
}
恩戈尼尼特(){
this.button2=新的基本按钮组件();
这个.setButtonText(“test1”);
}
}
问题是:第一个按钮渲染正确,而第二个按钮{{button2}}显示为[object]。我怎样才能告诉Angular将这个对象注入到模板中呢
提前感谢在
表单组件中模板
获取按钮2
对象的值:
{{button2.label}}
更新。
双大括号({{}})用于嵌套,而不是嵌套
要跨组件进行通信,请使用。(无需使用new
来创建组件实例,请选中此项:)
检查此示例:并尝试更好地解释您希望实现的功能。如果您希望调用子组件中的函数,而基本按钮组件是,最好使用
表单组件,第一次导入:
import { ViewChild } from '@angular/core';
然后在组件中:
@ViewChild(BasicButtonComponent) basicButtonComp: BasicButtonComponent;
setButtonText(t: string){
this.basicButtonComp.changeLabel(t);
}
这应该很管用!:) 这样标签就会显示出来,但我需要显示按钮,而不仅仅是标签。可能吗?