繁体   English   中英

Angular 5从父组件中的数组删除对象

[英]Angular 5 Deleting object from array in parent component

我是新手。

我正在Angular 5中创建一个报价清单网站。子组件“ Quotes”是用户互动的地方,而我要删除的表单数组位于app.component.ts中。 每个引用都是数组中的一个对象,当我单击删除按钮时,我希望删除整个对象,但我只会收到很多错误。 “ quotes”组件html中的当前删除按钮如下:

<a href (click)="delete(true)">
        <i class="trash icon"></i>
        Delete
      </a>

我的app.component.ts如下:

  delete(isComplete,index){
if (isComplete){
    let toDelete=confirm(`Are you sure you want to delete ${this.quotes[index]}`)

    if(toDelete){
        this.quotes.splice(index,1)
    }
}
}

我的app.component.html如下:

<div *ngFor="let quote of sortedQuotes(); let i = index" [quote]="quote">
  <app-quote 'deleteQuote($event,i)'>
  </app-quote>
</div>

由于添加删除功能损坏了某些内容,因此当前不起作用。 我收到错误消息:

Uncaught Error: Template parse errors:
Unexpected closing tag "app-quote". It may happen when the tag has 
already been closed by another tag. For more info see 
https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have- 
   implied-end-tags (" of sortedQuotes(); let i = index" [quote]="quote">
  <app-quote 'deleteQuote($event,i)'>
  [ERROR ->]</app-quote>
</div>
</div>"): ng:///AppModule/AppComponent.html@18:6
at syntaxError (compiler.js:485)
at DirectiveNormalizer._preparseLoadedTemplate (compiler.js:3220)
at eval (compiler.js:3200)
at Object.then (compiler.js:474)
at DirectiveNormalizer._preParseTemplate (compiler.js:3200)
at DirectiveNormalizer.normalizeTemplate (compiler.js:3178)
at CompileMetadataResolver.loadDirectiveMetadata (compiler.js:14908)
at eval (compiler.js:34412)
at Array.forEach (<anonymous>)
at eval (compiler.js:34411)

您需要EventEmitter将从子组件中发出事件

<app-quote (delete)='deleteQuote($event,i)'>
</app-quote>

component.ts必须是这样的

@Output() delete:EventEmitter<type> = new EventEmitter<type>();

onDeleteButtonClick() {
  //you need to emit event 
  delete.emit();
  // this can be done from button click mostly, which i am guessing is your case
}

而您的父component.ts将是

deleteQuote(event:type,i:type) {
}

暂无
暂无

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

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