我有几个分离的Web组件,由角元素组成,我在主要组件中导入,它有一个路由器,是基本应用程序。路线非常简单:
import { Component } from '@angular/core';
import { Router } from "@angular/router";
@Component({
selector: 'example',
template: '<component-one [variable]="toPass" (callback)="onCallback($event)"></component-one>',
styles: []
})
export class ExampleComponent {
public toPass: string = "Hello World!";
constructor(private router: Router) {}
onCallback(event) {
console.log(event);
this.router.navigate(['example-two']);
}
}
组件完成他们应该做的事情。
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: "component-one",
templateUrl: "./component-one.html",
styleUrls: ["./component-one.scss"],
encapsulation: ViewEncapsulation.Emulated,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ComponentOne implements OnInit {
@Input() variable: string;
@Output() callback = new EventEmitter<any>();
constructor() {}
ngOnInit() {
console.log("Variable: ", this.variable);
}
someRandomButtonClicked() {
callback.emit({ data: "Callback Called" });
}
}
现在,当我启动主应用程序时,一切都按预期显示,回调工作正常,但变量未定义。我在webcomponents的@Input声明中遗漏了什么?
由于您使用的是角度元素,请确保您的变量名称是小型的,如@Input() myvariable: string
而不是@Input() myVariable: string
,请点击此处https://github.com/angular/angular/issues/24871
我想你只是想念新的语法:)
当你在输入名称周围使用[]时,你会告诉angular你给他一个变量。如果你不使用它,你会要求角度将其作为基元。
所以:
<component-one [variable]="myVar"
必须在组件中定义名为“myVar”的var
没有
<component-one variable="myVar"
Angular将“myVar”作为字符串值
没用但工作:
<component-one [variable]="'myVar'"
您将新字符串作为变量
您只需在ComponentOne中启动变量即可。然后它应该工作
@Input() variable:String = “”;
改变这个:
export class ComponentOne
对此:
export class ComponentOne implements OnInit
并且不要忘记导入:
import { Component, OnInit, Input} from '@angular/core';
在您的代码中,在问题中显示的所有位置将String
更改为string
。看看它是否有效。
String
是string
类型的构造函数。更多信息here
见distinction between string and String。
更新:
我有一种感觉,它与您使用的内联模板格式有关。
改变这个
@Component({
selector: 'example',
template: '<component-one [variable]="toPass" (callback)="onCallback($event)"></component-one>',
styles: []
})
对此,
@Component({
selector: 'example',
template: `<component-one [variable]="toPass" (callback)="onCallback($event)"></component-one>`,
styles: []
})
看,我把template: ''
改成了这个
template: ``
否则,内联模板字符串的解析可能会搞砸。
看看是否有效。