首页 > 解决方案 > 角度输入不产生结果。在父组件中

问题描述

父.html

   <div>
        <p>form the parent</p>
        <app-child>[value]="from the parent"</app-child>
    </div>

child.html

<p>child works!</p>
<h1>{{value}}</h1>

child.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {


  @Input() value : string;

  constructor() { 

    }



  ngOnInit() {
    console.log(this.value);
  }

}

角度输入不产生结果。在父组件中。尽管我在子组件中使用了 value。

标签: angular

解决方案


这是因为您使用错误的语法将输入值传递给组件 - 您在组件标签指定输入值,因此 Angular 会将其视为您尝试将 HTML 传递给组件的<ng-content>. 相反,您应该像在 HTML 标记上指定属性一样指定它:

<div>
  <p>form the parent</p>
  <app-child [value]="from the parent"></app-child>
</div>

此外,您不应将value属性括在方括号中,因为 Angular 会将其视为您的组件模板中有一个名为from the parent. 但是由于您的组件中没有这样的属性,它可能无法正确呈现。相反,您应该将属性值括在单引号内或删除方括号:

<div>
  <p>form the parent</p>
  <app-child value="from the parent"></app-child>
</div>

或者:

<div>
  <p>form the parent</p>
  <app-child [value]="'from the parent'"></app-child>
</div>

有关更多信息,请查看Angular 模板语法文档的表达式上下文部分


推荐阅读