user327126
user327126

Reputation: 1077

Initialize and assign value in typescript

I have a component where I am passing input value preferredContactMethods.

I want to initialize another variable alternateContactMethods and assign same value as preferredContactMethods.

I tried:

Object.assign

@Input()
preferredContactMethods: Array<string>;

alternateContactMethods: Array<string> = Object.assign(this, this.preferredContactMethods);

Direct assign

@Input()
preferredContactMethods: Array<string>;

alternateContactMethods: Array<string> = this.preferredContactMethods;

nothing works

Any suggestion or example would be helpful.

Upvotes: 0

Views: 886

Answers (3)

Devang Patel
Devang Patel

Reputation: 1843

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
   }

}

Upvotes: 0

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

Angular provides you an interceptor for input property changes. This will provide you the opportunity to only set the value if your input changes. It will look like this:

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;
};

Upvotes: 1

CMS Develop
CMS Develop

Reputation: 90

 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;
   }

}

Upvotes: 0

Related Questions