有角度地将对象从一个组件添加到另一组件中的数组

时间:2019-02-26 15:26:46

标签: arrays angular components

我有2个组件及其模板,如下所示。当组件CreateitemComponent创建新项目时,我想将其放入itemsListComponent中的数组。第二个模板中的项目详细信息基本上会获取并显示项目。最简单的方法是什么?

//Create Item Component
@Component({
  selector: 'create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css'],
})
export class CreateitemComponent implements OnInit {

  item: Item=new Item();
  submitted = false;

  ngOnInit() {}
}

//Create Item Template
<h3>Create item</h3>
<div [hidden]="submitted" style="width: 300px;">
  <form (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="label">Label: </label>
      <input type="text" class="form-control" id="label" required [(ngModel)]="item.label" name="label">
    </div>

    <div class="form-group">
      <label for="price">Price: </label>
      <input type="text" class="form-control" id="price" required [(ngModel)]="item.price" name="price">
    </div>

    <button type="submit" class="btn btn-success">Submit</button>
  </form>
</div>

<div [hidden]="!submitted">
  <h4>You submitted successfully!</h4>
  <button class="btn btn-success" (click)="newitem()">Add</button>
</div>

//List Items Component
@Component({
  selector: 'item-list',
  templateUrl: './list-items.component.html',
  styleUrls: ['./list-items.component.css']
})
export class itemsListComponent implements OnInit {

  items: Item[];
}


//List Items Template
<h1>List of Items</h1>

<div *ngFor="let Item of items | async" style="width: 300px;">
  <item-details [item]='Item'></item-details>
</div>

<div>
  <button type="button" class="button btn-danger" (click)='deleteItems()'>Delete All</button>
</div>

1 个答案:

答案 0 :(得分:0)

这是一个用Subject完成的简单示例:https://stackblitz.com/edit/angular-xycafa?file=src%2Fapp%2Fapp.component.ts

这是简单的代码:

应用程序组件:

export class AppComponent  {
  constructor(private service: AppService){

  }

  addItem(item){
    const data =  {name: item};
    this.service.setData(data);
  }

}

html

<input type="text" #inp>
<button (click)="addItem(inp.value)">Add Item</button>
<br><br>
<list></list>

服务

@Injectable()
export class AppService{
  private data$ = new Subject<any>();
  public dataEvent = this.data$.asObservable();

  public setData(data){
    this.data$.next(data);
  }
}

列表组件

@Component({
  selector: 'list',
  template: `<ul *ngFor="let d of data"><li>{{d.name}}</li></ul>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class ListComponent  {
  data: string[] = [];

  constructor(private service: AppService){
    this.service.dataEvent
    .subscribe(res => {
      this.data.push(res);
    })
  }
}

基本上:主要成分是“谁”创建元素。 List组件处理它们。在这种情况下,这是一个基本示例,但这就是逻辑。