角度 2:从其他组件触发插值不工作



我有两个组件,C1和C2。 我想在单击 C2 中的按钮时触发 C1 中的插值。

插值在 C2 中定义为公共变量:

public elementType: string = "test";

C2 在 C1 中定义如下:

import {PropertiesComponent} from "../properties/properties.component";
constructor(private propComp: PropertiesComponent) {}
setActive(model){console.log("test");
this.propComp.elementType = "updated value";}

控制台日志已触发,但内插未触发。

您正在将组件视为服务。因此将其添加到构造函数和所有内容中。

您可以将 elementType 从 C2 作为 @Input(( elementType 传递给 C1,它将满足您的期望。

在 C1 中

@Input() elementType;
setActive(model){
console.log("test");
this.elementType = "updated value";
}

利用 Angular 服务来引用 C1 组件在 C2 组件中设置的值。 在两个组件中注入服务。 在服务中声明变量elementType。 在组件 C1 中设置服务的变量elementType。 现在,您可以通过服务实例在组件 C2 中访问它。

如果您不喜欢使用服务,则必须使用@Input()@Output()变量从 C1 传递到 C2。

正如@Padmapriya所说,您不能像服务一样注入组件。相反,您可以将组件用作子组件来交换数据。

最新更新