Angular 在typescript中初始化并赋值
我有一个组件,我在其中传递输入值preferredContactMethods 我想初始化另一个变量alternateContactMethods,并指定与preferredContactMethods相同的值 我试过: Object.assign 直接分配 什么都不管用 任何建议或示例都会很有帮助。Angular为您提供了一个解决方案。这将使您有机会仅在输入更改时设置值。它将如下所示:Angular 在typescript中初始化并赋值,angular,typescript,Angular,Typescript,我有一个组件,我在其中传递输入值preferredContactMethods 我想初始化另一个变量alternateContactMethods,并指定与preferredContactMethods相同的值 我试过: Object.assign 直接分配 什么都不管用 任何建议或示例都会很有帮助。Angular为您提供了一个解决方案。这将使您有机会仅在输入更改时设置值。它将如下所示: You need to do following to assign value: import { Co
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
}
}
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;
};
这只在组件初始化后工作一次。这只在组件初始化后工作一次。
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
}
}
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;
}
}
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;
};