【问题标题】:Angular component communication parent - child not workingAngular组件通信父子不工作
【发布时间】:2023-03-22 21:51:01
【问题描述】:

我遇到了父子组件之间的通信问题。 我有一个要放入子组件中的多个项目的列表,但另一方面,他不会填充子对象并给出未定义的另一个原因。父对象知道项目的数量,因此它被正确初始化,并且通过调试对象被填充。但在孩子中,未定义的内容可以填充我要放置 objectdata 的每张卡片。

让我们看看代码:

@NgModule({
  imports: [    
    BrowserModule,
    FormsModule,
    NgbModule,
    MaterialModule,
    AppRoutingModule,
    BrowserAnimationsModule,    
    LayoutModule    
  ],
  declarations: [    
    AppComponent,    
    PortalcardComponent,
    PortalcardsComponent,    
    ErrorPageComponent 
  ],  
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

是关于portalcarccomponent,以及app.module.ts中的portalcardscomponents

<app-portalcards>        
</app-portalcards> 

这是 app.component.html 中的标签

import { Component, Output } from '@angular/core';
import { PortalCardData } from '../../../core/interfaces/portalcard'

@Component({
  selector: 'app-portalcards',
  templateUrl: './portalcards.component.html',  
  styleUrls: ['./portalcards.component.scss']
})
export class PortalcardsComponent {
  portalcards = PortalCardData;  
}

portalcards.component.ts

<app-portalcard *ngFor="let portalcard of portalcards">      
    [portalcard]="portalcard"
</app-portalcard>

portalcard.component.ts

import { Component, Input } from '@angular/core';
import { PortalCard } from '../../interfaces/portalcard'

@Component({
  selector: 'app-portalcard',
  templateUrl: './portalcard.component.html',
  styleUrls: ['./portalcard.component.scss']
})
export class PortalcardComponent{
  @Input() portalcard: PortalCard  
}

portalcard.component.html

<div class="card">
  <img src="..." class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">{{portalcard.title}}</h5>
    <p class="card-text">{{portalcard.subtitle}}</p>
    <a href="" (click)="false" class="btn btn-primary mt-2">{{portalcard.button.title}}</a>
  </div>
</div>

它可能很小,但我看不到它:(。也许有人可以在这里帮助我。

谢谢。问候马克

这些是谷歌开发者工具栏中的错误。 2 项。 2 个错误。

enter image description here

【问题讨论】:

  • 根据此来源 - angular.io/api/core/Input,输入参数应作为 DOM 属性发送,因此您必须将 [portalcard]="portalcard" 作为参数发送,靠近该 ngFor

标签: angular parent-child angular-components


【解决方案1】:

试试这个:

<app-portalcard *ngFor="let portalcard of portalcards" [portalcard]="portalcard">          
</app-portalcard>

代替你的代码:

<app-portalcard *ngFor="let portalcard of portalcards">      
    [portalcard]="portalcard"
</app-portalcard>

【讨论】:

  • 谢谢 Peter 和 Belle(部分正确)...这很有魅力
【解决方案2】:

据我所知,portalcards = PortalCardData 是单数类型而不是数组。它应该首先定义为一个数组,以便可以使用*ngFor 对其进行迭代。

你可以试试改成这个 portalcards = PortalCardData[]

并用这个正确插入输入

<app-portalcard *ngFor="let portalcard of portalcards" [portalcard]="portalcard">      
</app-portalcard>

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2016-04-12
    • 2016-12-03
    • 1970-01-01
    • 2021-03-02
    • 2018-12-22
    • 1970-01-01
    • 2017-10-12
    • 2021-01-15
    相关资源
    最近更新 更多