angular - 如何将@Input 发送到多个组件?
问题描述
我想将@Input() 发送到两个不同的组件:一个是列表项,另一个是项详细信息。他们应该使用或多或少相同的属性。
我尝试使用不同的服务来发送相同的输入,无论是否使用 Observable 和订阅,但是当我尝试显示我的项目详细信息组件时,我总是收到相同的错误消息:“无法读取未定义的属性”属性“。列表项工作正常。
这是我的代码:
列表 HTML:
<div class="container list-group">
<a *ngFor="let actu of actus" class="list-group-item list-group-item-action flex-column align-items-start" [routerLink]="['/article', actu.id]">
<app-item-actus [actu]="actu"></app-item-actus>
</a>
<div *ngFor="let actu of actus" class="hide">
<app-actu-detail [article]="actu" class="hide"></app-actu-detail>
</div>
<br>
</div>
在这里,我尝试使用隐藏的 *ngFor 将我的项目发送到详细信息(class="hide" 是显示:无)。
列出 TS:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ActuService } from 'src/app/services/actu.service';
import { Actu } from '../../../modeles/actu';
@Component({
selector: 'app-liste-actus',
templateUrl: './liste-actus.component.html',
styleUrls: ['./liste-actus.component.css']
})
export class ListeActusComponent implements OnInit {
actus: Actu[];
constructor(private actuService: ActuService) {
}
ngOnInit() {
this.actuService.getActusList().subscribe(data => { this.actus = data; });
}
}
我没有使用 Observable 来检查结果是否相同,但似乎没有任何变化。
项目详细信息 HTML
<div>
<h2>{{article.titre}}</h2>
<br>
<blockquote *ngIf="article.exergue"><i>{{article.exergue}}</i>
</blockquote>
<br>
<figure>
<img *ngIf="article.image" src="{{article.image}}" alt="image article">
<figcaption>{{article.legendeImage}}</figcaption>
</figure>
<br>
<p *ngIf="article.paragraphe1">{{article.paragraphe1}}</p>
<br>
<h4 *ngIf="article.intertitre1">{{article.intertitre1}}</h4>
<br>
<p *ngIf="article.paragraphe2">{{article.paragraphe2}}</p>
<br>
<h4 *ngIf="article.intertitre2">{{article.intertitre2}}</h4>
<br>
<p *ngIf="article.paragraphe3">{{article.paragraphe3}}</p>
<br>
</div>
这是我的项目详细信息 HTML,它与我的列表项目或多或少相同,但要显示更多属性。
项目详细信息 TS
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-actu-detail',
templateUrl: './actu-detail.component.html',
styleUrls: ['./actu-detail.component.css']
})
export class ActuDetailComponent implements OnInit {
@Input() article: any;
constructor() { }
ngOnInit() {
}
}
我使用 spring 生成的项目 + mysql 作为 back 和 DB,我是编码世界的新手,所以我可能在某个地方犯了一些大错误,但我不知道在哪里。
提前感谢您对我的问题的帮助。
解决方案
我认为您应该添加一个 *ngIf 以确保您的数据在循环之前定义:
<div class="container list-group" *ngIf="actus">
...
</div>
如果您想在获取数据时避免出现白屏,则必须使用解析器https://angular.io/api/router/Resolve
推荐阅读
- angular - 角度,ngFor,索引
- react-native-android - React Native 高度和绝对位置
- angular - Angular 2 - 向表格单元格中的按钮添加点击功能
- python - Python在外部函数调用上定义嵌套函数的参数
- automation - 如何使用 AppleScript 让 Arcobat 自动将 PDF 转换为图像(JPEG)
- sql - 如何使用 SQL 查询从员工的给定反馈中获得最满意的部门
- android - 如何使用已存在的 DISPLAY_NAME 添加新联系人?
- angular - 角度组件中的附加资源参考
- javascript - 更改表单“方法”不起作用,浏览器发出“GET”请求
- java - 当 Spring/Hibernate JPARepository 返回时,Entties 处于什么生命周期状态?