首页 > 解决方案 > 角度中的输入装饰器无法正常工作

问题描述

我想将一些属性绑定到 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>

标签: angular

解决方案


这种情况下的问题是“配方”最初是未定义的。即使您在 RecipeListComponent 中创建它,它也不会在构造时直接传递给其他组件。(因此,console.log 将返回 undefined)

你可以做什么:将你的 div 包裹在 recipe-item-component html 中*ngIf="recipe"


推荐阅读