1

这是代码:

app.component.html

<input type="text" [(ngModel)]="newAreaName"/><button (click)="addItem()" [disabled]="editing ? false : true">ADD</button>
<button (click)="toggleEditing()">{{ editing ? 'Cancel' : 'Edit'}}</button>
<app-line (layout)="setFloorLayout($event)" [editing]="editing" [newAreaName]="newArea"></app-line>

app.component.ts

flrLayout = [];
  editing = true;

  newAreaName = "";
  newArea = "";

  setFloorLayout(data: any) {
    this.flrLayout = data;
  }

  addItem(): void {
this.newArea = this.newAreaName;
this.newAreaName = "";
console.log(`SUCCESS ADDING`);
  }
  toggleEditing() {
    this.editing = !this.editing;
  }

子组件 line.component.ts

@Input() newAreaName: string;
  @Output() layout: EventEmitter<any> = new EventEmitter();
  @Input() editing: any;

  options: Safe;

  dashboard = [];

  ngOnInit() {}

  ngOnChanges() {
    console.log(this.dashboard);
    if (this.newAreaName && this.editing) {
      this.addItem(this.newAreaName);
    }
  }
  addItem(areaName: string): void {
    this.dashboard.push({ x: 0, y: 0, cols: 1, rows: 1, area: areaName });
    this.layout.emit(this.dashboard);
  }

这里的问题是在添加新数据之后,当我单击取消然后当我尝试单击编辑按钮时,它会自动附加新数据。相反,仪表板数组将为空。

这是代码和输出:https ://stackblitz.com/edit/angular-rc7bbz?file=src%2Fapp%2Fapp.component.ts

注意:添加数据后,单击取消然后单击编辑按钮。

假设有一个现有数据

dashboard = [{
area: "Area1"
cols: 1
rows: 1
x: 0
y: 0
}]

然后添加一个“Area2”数据应该是这样的。

 dashboard = [{
    area: "Area1"
    cols: 1
    rows: 1
    x: 0
    y: 0
    },{
    area: "Area2"
    cols: 1
    rows: 1
    x: 0
    y: 0
    }]

然后当它单击取消按钮并单击编辑按钮时,它应该是这样的:

dashboard = [{
        area: "Area1"
        cols: 1
        rows: 1
        x: 0
        y: 0
        }]
4

2 回答 2

1

line.component.ts包含以下行


  ngOnChanges() {
    if (this.editing) {
      this.addItem(this.newAreaName);
    }
  }
  addItem(areaName: string): void {
    this.dashboard.push({ x: 0, y: 0, cols: 1, rows: 1, area: areaName });
    this.layout.emit(this.dashboard);
  }

每次以下输入之一

  @Input() newAreaName: string;
  @Input() editing: any;

在编辑为真时更改,将推送一个新项目。

这不是一个好习惯,基本上,您是从组件创建元素,使用文本输入更改事件作​​为触发器。您可能想要更改逻辑并在应用程序行组件内添加按钮(或该组件外部的 addItem)

我能想到的一个快速但有点丑陋的解决方案是使用布尔值作为触发器 =>

https://stackblitz.com/edit/angular-9geygo?file=src/app/line/line.component.ts

于 2020-10-29T02:16:26.630 回答
0

您可以更新您的 ngOnChanges。这是一个可行的解决方案,可以满足您的要求。

  1. 我设置了一条默认记录(区域:“Area1”)

  2. 如果您添加一条新记录(区域:“Area2”),它会将其添加到数组中

  3. 如果您单击取消,它将删除最后一个元素

  4. 如果您单击编辑,您可以看到您的默认元素

    ngOnChanges() {
      if ((this.editing && !this.wasItemRemoved) || 
       this.isAddButtonPressed) {
       this.addItem(this.newAreaName);
       this.wasItemRemoved = false;
     }else {
       if (this.dashboard.length > this.elementsSize) {
       this.dashboard.pop();
       this.wasItemRemoved = true;
     }
     this.layout.emit(this.dashboard)
     }
    }
    

现场演示

于 2020-10-29T03:05:26.870 回答