angular属性绑定是否有聚合的写法

component1 有多个@input输入属性,使用时能否通过一个对象完成多个属性的绑定,而不是对每个属性使用[]进行绑定?
或者是否存在方法从类中直接绑定?

目前研究过hostbinding和动态组件方案,前者只能绑定html原生的属性,而且只适用于宿主元素,后者是可以手动改变组件instance属性的值,但没有建立绑定关系。

主要是为了大量属性绑定的时候写起来简洁方便。

阅读 1.2k
1 个回答

如果是动态组件的话,可以考虑这样写

 data: { name: string, age: number; } = {name: '12', age: 22};
  @ViewChild('container', {static: true, read: ViewContainerRef})
  container!: ViewContainerRef;
  constructor(private renderer2: Renderer2, private componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit(): void {
    const com: ComponentFactory<UserComponent> = this.componentFactoryResolver.resolveComponentFactory(UserComponent);
    const userComponentComponent = this.container.createComponent(com);
    Object.assign(userComponentComponent.instance, this.data); //set input
  }

绑定关系的话,似乎没有什么好办法,只能每次都重新set一下input的值
比如变更后再次调用
Object.assign(userComponentComponent.instance, this.data);

如果是为了多个属性输入方便的话,在组件设计的时候,就可以考虑用object来接收对象
如果是第三方组件,那好像没什么办法了

/*@Input()
  name!: string;
  @Input()
  age!: number;*/
  @Input()
  userInfo: { name?: string, age?: number; } = {};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题