【问题标题】:How to set value in child from parent?如何从父母那里设置孩子的价值?
【发布时间】:2018-09-22 22:46:43
【问题描述】:

我有这个笨蛋:

https://plnkr.co/edit/5XbuxoGG6NqomayLP4Ae?p=preview

我有这个:

> @Component({   selector: 'my-app',   template: `
>     <layout [child]="childModal">
>      <div class="body">
>       <common-modal  #childModal [title]="'common modal'"> 
>     <div class="modal-body">
>     {{5+7}} {{item}}
>     Hi heloo </div>
>     </common-modal> 
>      </div>
>     </layout>
>     <button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button>
>    
> 
>   `, })

export class AppComponent {
  @ViewChild('childModal') childModal :CommonModalComponent;
  item:number=150;
  constructor(private viewContainerRef: ViewContainerRef) {
  }

}

如何在布局组件中设置应用组件中的项目。有什么建议吗?我的问题是如果我没有子级父组件和其他一些组件,如何从父级设置子变量。

<parent>
<some-other-component></some-other-component>
</parent>

我没有孩子的选择器。 如何更改 AppComponent 中项目的布局组件值?

编辑: 这就是我想要做的: https://plnkr.co/edit/BVS2AlQNZ7kO5wbsTBaA?p=preview

但由于某种原因,emit 无法正常工作。

【问题讨论】:

  • 不清楚您要完成什么。你能解释一下吗?
  • 如何更改 AppComponent 中项目的布局组件值..
  • 您已经在使用 'item' 执行此操作 - 您将其设置为 150。您可以为 'item' 分配不同的值,它将反映在对话框中。
  • 我想点击某个按钮上的布局组件来更改项目的 appcomponent 中的值。现在我有固定值,我想在布局组件中添加按钮,当我单击该按钮以设置 item = 200 时。没关系它只是我想从布局中更改它的值
  • 你的意思是这样的? plnkr.co/edit/VsgJTBGfeFUPiHb5tqcK?p=preview

标签: angular


【解决方案1】:

您需要为布局组件内的项目创建一个输入变量,并为您的应用程序组件发出一个事件来处理它并更改项目变量的值。

应用组件

@Component({
  selector: 'my-app',
  template: `
    <layout [child]="childModal" [item]="item" (itemChange)="onItemChange($event)">
     <div class="body">
      <common-modal  #childModal [title]="'common modal'"> 
        <div class="modal-body">
          {{5+7}} {{item}}
          Hi heloo
        </div>
      </common-modal> 
     </div>
    </layout>
    <button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button>


  `,
})
export class AppComponent {
  @ViewChild('childModal') childModal :CommonModalComponent;
  item:number=150;
  constructor(private viewContainerRef: ViewContainerRef) {
  }
  onItemChange(item) {
    this.item = item;
  }
}

布局

import {Component,Input, Output, ViewChild, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'layout',
  template: `
    <div class="modal-body">
    <button (click)="show()">CLICKKK</button>
        <ng-content select="div.body"></ng-content>
      </div>
  `,
})
export class Layout {
   @Input() title?:string;
   @Input() child;
   @Input() item;
   @Output() itemChange: EventEmitter = new EventEmitter;
  constructor() {
  }
  show() {
   this.item = 200;
   this.child.show();
   this.itemChange.emit(this.item);
  }

}

编辑: 我想你还没有理解我的回答……所以看看这个链接:https://plnkr.co/edit/mFcoiXqFedN1RO7tsETX?p=preview

我把它编码并添加了一些cmets来解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多