Rin and Len
Rin and Len

Reputation: 507

How do I work on data from @input in Angular?

New to Angular so be nice...

I have a component that get a date/string value from a parent component:

export class myComponent implements OnInit {
    @Input() myDate: string;

    constructor(){}

    ngOnInit(){}
}

The problem I have is that I want to use split() method on the @Input myDate string so that I can use the parts (array indexes assigned to vars) in the view individually.

I tried following the Angular guide and ended up with this in my class:

private _myDate;
@Input()
set myDate(myDate: string){
    this._myDate = (myDate && myDate.split(' '));
}
get myDate(): string { return this._myDate };

but that returns undefined cannot and I don't know if the code I need to write goes in the class or in the constructor (because I see conflicting info all over the web).

Variation on above returns "Property split does not exist on type 'String[]'" which akes sense, but I can't seem to find out how to avoid either that error or in the first code sample, cannot convert type string to array:

private _myDate = [];
@Input()
set myDate(myDate: Array<String>){
    this._myDate = (myDate && myDate.split(' '));
}
get myDate(): Array<String> { return this._myDate };

So, how do I do work on the @Input myDate value and where do I do it?

Upvotes: 2

Views: 174

Answers (3)

Batajus
Batajus

Reputation: 6257

To achieve your wished goal you can do follow:

private _myDate: string[];

@Input() 
set myDate(myDate: string){ // You're receiving a string, so the correct typing is string and not Array<string>

    // For a clean 'string' you need to remove the , from your given value
    let cleanDate: string = myDate.replace(',', ''); 

    // After you've removed the , you can simply split the string to get your array
    this._myDate = cleanDate.split(' ');
}

get myDate(): string { return this._myDate };

I hope my comments are understandable ;-)

Upvotes: 2

Anjil Dhamala
Anjil Dhamala

Reputation: 1622

I normally don't use a setter but I can assume you can just do this and achieve what you want.

<your-component-selector [myDate]="somePropertyInParentClass"></your-component-selector>

Child component would look something like this:

export class YourComponent implements AfterViewInit {
  @Input() myDate: any;

  ngAfterViewInit() {
    this.myDate = this.myDate.split(" ");
  }
}

After that, just loop over your myDate prop using *ngFor in your view.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

You can use it inside ngOnChanges

 ngOnChanges(changes: SimpleChanges) {
   if (changes['myDate']) {
     this._myDate = (myDate && myDate.split(' '));
   }
 }

Upvotes: 1

Related Questions