如何处理Angular中@input的数据?

时间:2018-08-21 18:49:50

标签: angular angular6

是Angular的新手,所以要好...

我有一个从父组件获取日期/字符串值的组件:

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

    constructor(){}

    ngOnInit(){}
}

我的问题是我想对@Input myDate字符串使用split()方法,以便可以在视图中单独使用部件(分配给vars的数组索引)。

我尝试按照Angular指南进行操作,并最终在课堂上完成了此操作:

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

但是返回 undefined 却不能,而且我不知道我需要编写的代码是否在类中或在构造函数中(因为我在网上看到的信息冲突)。

上面的变化返回了“字符串拆分”,“属性拆分不存在”,但是我似乎无法找出如何避免该错误或者在第一个代码示例中无法转换类型的方法字符串到数组:

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

那么,我该如何使用@Input myDate值以及在哪里进行操作?

3 个答案:

答案 0 :(得分:2)

要实现理想的目标,您可以执行以下操作:

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

我希望我的评论是可以理解的;-)

答案 1 :(得分:1)

您可以在 ngOnChanges

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

答案 2 :(得分:1)

我通常不使用二传手,但我可以假设您可以做到这一点并实现您想要的。

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

子组件看起来像这样:

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

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

此后,只需在视图中使用myDate遍历*ngFor道具即可。