2 回答

TA贡献1812条经验 获得超5个赞
在我看来,最好在模型中定义它们
您将从以下模型开始
params.model.ts
import {SomeOtherModel} from './some-other.model'
export interface ParamsModel {
paramName1: string;
paramName2?: string;
paramName3?: number;
paramName4: SomeOtherModel;
}
然后在您的组件中,您可以强制您的输入采用特定的模型参数
my.component.ts
import {ParamsModel} from './params.model';
@Component({..})
class MyComponent {
@Input() params: ParamsModel;
}
app.component.html
<my-component params="paramsModel"></my-component>
app.component.ts
import {ParamsModel} from './params.model';
@Component({..})
class AppComponent implements OnInit {
paramsModel: ParamsModel;
ngOnInit(): void {
this.paramsModel = <ParamsModel>{someValue: someValue};
}
}
这样你就有了完整的代码完成。
不过请注意!Angular 不会深入观察内容,因此更改 Params 对象内部的内容,在 javascript 中仍然具有相同的对象 ID,导致 angular 看不到更改。
有一些解决方法
1:绑定每个参数(这正是你不想要的)
2:改变模型内容的时候,每次都销毁实例并创建一个新的实例,你可以通过在模型中添加一个构造函数并像这段代码一样转换它来做到这一点
export class ParamsModel {
paramName1: string;
paramName2?: string;
paramName3?: number;
paramName4: SomeOtherModel;
constructor(config?: ParamsModel) {
Object.assign(this, config);
}
}
// first init
this.paramsModel = new ParamsModel(<ParamsModel>{someValue: someValue});
// updated init
this.paramsModel = new ParamsModel(this.paramsModel);
this.paramsModel.changedValue = changedValue; // (could also use an extend function on original params model)
3:创建一个带有事件的观察者,并在另一端触发更新事件
4:使用 ngDoCheck 自行检查内容是否发生变化

TA贡献1877条经验 获得超1个赞
在 Angular 中没有传递输入属性的通用指令。但是,Angular 支持绑定任何有效的 JavaScript 类型,无论是对象、数组还是原语。
在模板中
<my-component [params]="params"/>
在类中,您必须使用@Input装饰器将对象标记为输入。您可以在任何生命周期挂钩中访问它的值,如下所示。请注意,params不会在构造函数中设置,因为在类实例化后执行视图绑定。
class MyComponent {
@Input()
params: any
constructor() { } // <-- params not set
ngOnChanges() { } // <-- anytime params changes
ngOnInit() { } // <-- once when the component is mounted
}
添加回答
举报