【问题标题】:Pass props using ES6 spread operator使用 ES6 扩展运算符传递道具
【发布时间】:2021-07-28 08:50:16
【问题描述】:

ChildComponent.ts

export class ChildComponent implements OnInit {
  @Input() name?: string;
  @Input() email?: string;
  // A lot more props

  constructor() {}

  ngOnInit(): void {}
}

ParentComponent.ts

export class ParentComponent implements OnInit {
  childProps = {
    name: "johnny",
    email: "johnny@gmail.com"
  };

  constructor() {}    
  ngOnInit(): void {}
}

ParentComponent.html

这行得通:

<app-child [name]="childProps.name" [email]="childProps.email"></app-child>

但是如何使用 ES6 扩展运算符传递所有道具?

<app-child [*]="{...childProps}"></app-child>

【问题讨论】:

标签: angular typescript


【解决方案1】:

你可以考虑为props定义一个接口,然后作为一个对象传递,不需要传播或使用多个@Inputs()

// child.ts

export interface ChildProps {
  name?: string,
  email?: string  ​
}

export class ChildComponent implements OnInit {
 ​@Input() allProps?: ChildProps;
​
 ​constructor() {}

 ​ngOnInit(): void {}
}
//parent.ts

export class ParentComponent implements OnInit {
  childProps = {
    name: "johnny",
    email: "johnny@gmail.com"
  };

  constructor() {}    
  ngOnInit(): void {}
}
<!-- parent-template.html -->

<app-child [allProps]="childProps"></app-child>
<!-- child-template.html -->

<div>{{ allProps?.name }}</div>

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多