在父组件中调用子方法

时间:2020-06-09 12:26:53

标签: javascript html angular

我有两个组成部分。一个是父母,第二个是孩子。

我想做的是在子组件中添加新元素(现在是简单的div)。

当我单击子html中的按钮(添加托盘)时,它正在工作。

当我单击父HTML上的按钮(添加托盘)时,它不起作用。

它正在创建托盘的新实例,但是此div不会在子HTML上显示。 console.log中的结果相同。

子组件:



import { Component } from "@angular/core";
import { Pallet } from '../pallet.model';


@Component({
  selector: 'app-workspace',
  templateUrl: './workspace.component.html',
  styleUrls: ['./workspace.component.css']

})

export class WorkspaceComponent  {
  pallets: Pallet[] = [];

addPallet1(){

  let temp = new Pallet();
  temp.palletName = 'Pallet'+(this.pallets.length+1);
  temp.id=(this.pallets.length+1).toString();
  temp.width = "500";
  this.pallets.push(temp);
  console.log(temp); /*=>> 

Pallet {palletName: "Pallet1", id: "1", width: "500"}
id: "1"
palletName: "Pallet1"
width: "500"
__proto__: Object

*/

}
ngOnInit(){}

子HTML:

<div id="workspace" class="workspace">
   <div class="workspace-box" cdkDrag >

    <button (click) = "addPallet1()">Add Pallet</button> 
<button (click) = "check()">check</button>
    <div class="pallet" *ngFor="let pallet of pallets; let index=index" cdkDrag [ngStyle]="{'width.px': pallet.width }">

      <div
      [(ngModel)]="pallet.palletName"
      name="{{pallet.palletName}}"
      id="{{pallet.id}}"
      ngDefaultControl>
        <label>{{pallet.palletName}}</label>        
      </div>      
    </div>
  <div>


父html:

<button (click)="appChildWorkspace.addPallet1()">Add Pallet</button>
<app-workspace #appChildWorkspace></app-workspace>

0 个答案:

没有答案