【问题标题】:Angular 5 Deleting object from array in parent componentAngular 5从父组件中的数组中删除对象
【发布时间】:2018-08-27 23:23:14
【问题描述】:

我是角度新手。

我正在 Angular 5 中创建一个报价列表网站。子组件“报价”是用户交互的地方,而我要删除表单的数组位于 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)

【问题讨论】:

  • 你有一个没有属性name的值,大概你错过了(click)=
  • 这对你有用吗???

标签: javascript html angular typescript angular5


【解决方案1】:

你需要 EventEmitter 来从你的子组件发出事件

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

child 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) {
}

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多