我有一个要传递输入值PreferredContactMethods的组件。
我要初始化另一个变量AlternativeContactMethods并为preferredContactMethods分配相同的值。
我尝试过:
Object.assign
@Input()
preferredContactMethods: Array<string>;
alternateContactMethods: Array<string> = Object.assign(this, this.preferredContactMethods);
直接分配
@Input()
preferredContactMethods: Array<string>;
alternateContactMethods: Array<string> = this.preferredContactMethods;
没有用
任何建议或示例都会有所帮助。
答案 0 :(得分:1)
Angular为您提供了interceptor for input property changes。这将为您提供仅在输入更改时设置值的机会。看起来像这样:
private _preferredContactMethods: Array<string>;
private _alternateContactMethods: Array<string>;
// Here you can set/compare/calculate/... when your input changes
@Input() set preferredContactMethods(args: Array<string>){
this._preferredContactMethods = args;
this._alternateContactMethods = args;
};
答案 1 :(得分:0)
You need to do following to assign value:
import { Component, Input, OnInit } from '@angular/core';
export class YourComponent implements OnInit {
@Input() preferredContactMethods: Array<string>;
public alternateContactMethods: Array<string>
ngOnInit(): void {
console.log(this.preferredContactMethods); // To check value is exist or not.
this.alternateContactMethods = [...this.preferredContactMethods];. // Assign the copy of preferredContactMethods array
}
}
答案 2 :(得分:0)
Patent component html file like this:
<Your-Component [preferredContactMethods]="data" ></Your-Component>
Child Component.ts file
import { Component, Input, OnInit } from '@angular/core';
export class YourComponent implements OnInit {
@Input() preferredContactMethods: Array<string>;
alternateContactMethods: Array<string>
ngOnInit(): void {
console.log(this.preferredContactMethods); // To check value is exist or not.
this.alternateContactMethods = this.preferredContactMethods;
}
}