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

时间:2018-03-19 11:52:06

标签: javascript html angular typescript angular5

我是棱角分明的新人。

我正在Angular 5中制作一个引用列表网站。儿童组件"行情"是我想要删除表单的数组在app.component.ts中用户交互的位置。每个引用都是数组中的一个对象,我想在单击删除按钮时删除整个对象,但我只是遇到了大量错误。 "引号中的当前删除按钮"组件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)

1 个答案:

答案 0 :(得分:3)

你需要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
}

parent component.ts 将是

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