简体   繁体   English

从不更新父项的子项更新@Input属性

[英]update @Input property from child not updating parent

I am wanting to update an @Input property from a child and for the changes to take effect on the parent.我想更新子项的 @Input 属性并使更改对父项生效。

Parent TS (document-details):父 TS(文档详细信息):

export class DocumentDetailsComponent implements OnInit {
  view: string = 'editor';
}

Parent HTML (document-details):父 HTML(文档详细信息):

<document-content [(view)]="view" ></document-content>

Child TS (document-content):子 TS(文档内容):

export class DocumentContentComponent implements OnInit, OnChanges {

  @Input() view: string;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.version) {
      this.view = 'editor';
    } 
  }
}

When the view property inside the child component gets set top 'editor' it doesn't seem to reflect these changes inside the parent component.当子组件内的视图属性设置为顶部“编辑器”时,它似乎并未反映父组件内的这些更改。

I know I could use an @Ouput event emitter but I feel like this should work fine.我知道我可以使用 @Ouput 事件发射器,但我觉得这应该可以正常工作。

When angular bootstraps it builds a component tree.当角度引导时,它会构建一个组件树。 零件

A component has input and output properties, which can be defined in the component decorator or using property decorators.组件具有输入和输出属性,可以在组件装饰器中定义或使用属性装饰器。

Data flows into a component via @input properties(Parent to child ).数据通过@input properties(Parent to child)流入组件。 Data flows out of a component via @output (child to parent) properties.数据通过@output (子到父)属性流出组件。

with @input property data flows down the tree.It doesn't flow upwards.具有@input属性的数据沿着树向下流动。它不会向上流动。

if you want data flow in the opposite direction ie Upwards you need to use @Output decorator and Event emitter.如果您希望数据流向相反的方向,即向上,您需要使用@Output装饰器和事件发射器。

If you want changes from an @Input to affect the parent that means you want your @Input to also be an @Output , this is called two-way binding to which you can find the documentation here .如果您希望来自@Input的更改影响父级,这意味着您希望您的@Input也是一个@Output ,这称为two-way binding ,您可以在此处找到相关文档。

But in summary what happens is that in angular this:但总而言之,在角度上会发生什么:

<document-content [(view)]="view" ></document-content>

Is syntactic sugar for this:这是语法糖:

<document-content [view]="view" (viewChange)="view=$event" ></document-content>

So in order for your code to work you need to create the viewChange output and call emit() whenever your code changes the view property.因此,为了让您的代码正常工作,您需要创建 viewChange 输出并在您的代码更改视图属性时调用 emit()。

@Input() view: string;
@Output() viewChange = new EventEmitter<string>();

ngOnChanges(changes: SimpleChanges) {
  if (changes.version) {
    this.view = 'editor';
    this.viewChange.emit(this.view);
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM