angular - 角度中的输入装饰器无法正常工作
问题描述
我想将一些属性绑定到 DOM,但 @input 不起作用!编译时没有错误,但浏览器不知道属性!注意:浏览器无法识别名称、描述等属性!注意:recipe-item 是 recipe-list 组件的子组件!
这是配方列表组件:
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe.model';
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {
recipes: Recipe[] = [
new Recipe(
'a test recipe',
'this is just a test',
'some https address')
,new Recipe(
'a test recipe',
'this is just a test',
'some https address')];
constructor() {
}
ngOnInit(): void {
}
}
这是 recipe-list-component.html 文件:
<div class="col-xs-12">
<app-recipe-item
*ngFor="let recipeEL of recipes"
[recipe]="recipeEl"
></app-recipe-item>
</div>
这是配方列表组件:
import { Component, Input, OnInit } from '@angular/core';
import { Recipe } from '../../recipe.model';
@Component({
selector: 'app-recipe-item',
templateUrl: './recipe-item.component.html',
styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
@Input() recipe: Recipe;
constructor() {
console.log(this.recipe)
}
ngOnInit(): void {
}
}
这是配方项目组件 html 文件:
<a href="#" class="list-group-item clearfix">
<div class="pull-left">
<h4 class="list-group-item-heading">
{{recipe.name}}
</h4>
<p class="list-group-item-text">
{{recipe.description}}
</p>
</div>
<span class="pull-right">
<img [src]="recipe.imagePath" alt="{{recipe.name}}" class="img-responsive" style="max-height: 50px">
</span>
</a>
解决方案
这种情况下的问题是“配方”最初是未定义的。即使您在 RecipeListComponent 中创建它,它也不会在构造时直接传递给其他组件。(因此,console.log 将返回 undefined)
你可以做什么:将你的 div 包裹在 recipe-item-component html 中*ngIf="recipe"
推荐阅读
- github - 有什么方法可以动态替换 Github 存储库中的部分代码?
- android - 是否可以从 Fragment 获取“RecyclerView”?
- jquery - 如果包含十进制数,则将类添加到跨度
- java - Appium Java testNG Framework:驱动程序无法解析为变量
- c# - 在 MVC 控制器中共享相同数据集的多个 AJAX 调用
- php - 我正在尝试使用 PDO Fetch 对象从我的数据库中检索数据
- angular - angular material mat-select 在 Firefox 中看起来是空的
- c# - 使用 Log4Net 记录到多个文件
- ios - 带有 label.text 值的 Swift 本地通知自定义警报声音
- ruby - 正确使用 ruby exec 语法