【问题标题】:Not able to pass data from parent to child component in angular4无法在angular4中将数据从父组件传递到子组件
【发布时间】:2018-02-12 18:59:52
【问题描述】:

当我尝试将数据从父组件传递到子组件时出现错误。

这是我在父组件中放置的标签。

<pop-up [showPopUp]="true" [content]="content" [title]="title goes here"></pop-up>

子组件

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


@Component({
  selector: 'pop-up',
  templateUrl: './pop-up.component.html',
  styleUrls: ['./pop-up.component.css']
})
export class PopUpComponent implements OnInit {
  @Input()
  showPopUp: boolean;
  @Input()
  title: string = "";
  @Input()
  content: string = "";

  constructor() {
  }
  ngOnInit() {
    debugger;
  }
  proceed() {
    this.showPopUp = true;
  }
  closePopUp() {
    this.showPopUp = false;
  }
}

我想像这样在HTML中使用变量showPopUp,标题和内容

 <h5 class="modal-title" id="exampleModalLabel">{{title}}</h5>
 <h5 class="modal-title" id="exampleModalLabel">{{content}}</h5>

但是当我尝试使用它时,我得到了错误

我不确定我到底做错了什么。

【问题讨论】:

    标签: angular angular-components


    【解决方案1】:
    [title]="title goes here"
    

    应该是

    [title]="'title goes here'"
    

    title="title goes here"
    

    您的原始代码尝试将表达式title goes here 的值分配给title,但这不是有效的表达式。 您可以将表达式设为字符串字面量,或删除 [],这样 Angular 就不会尝试将值解释为表达式。

    【讨论】:

    • 谢谢,我能知道它采用这种格式的原因吗
    • 我已经在我的答案中添加了一个解释(你可能还没有看到它,因为我在最初的帖子之后编辑了我的答案)。 [] 是特殊的 Angular 绑定语法。
    猜你喜欢
    • 2018-02-15
    • 2018-08-25
    • 2021-02-22
    • 2018-05-01
    • 2019-02-27
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多