Angular使用@Input接收父组件数据的两种方式

本文介绍了Angular中使用@Input装饰器从父组件向子组件传递数据的两种方法。第一种方式简单直接,数据可在模板中直接使用;第二种方式则有利于在数据传递过程中进行拦截处理,但无法直接在模板中使用输入数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、父组件的代码

// parent.component.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.styl']
})

export class ParentComponent implements OnInit {

  public inputData = 'inputTest';

  constructor() { }

  ngOnInit(): void {
  }

}

// parent.component.html

<p>
    <app-child [inputData]="inputData"></app-child>
</p>

2、子组件的代码

<1>、第一种接收方式,不便于对数据进行切面拦截,inputData可以作为属性在模板中直接使用。

// child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.styl']
})

export class ChildComponent implements OnInit {

  @Input()
  public inputData: string;

  constructor() { }

  ngOnInit(): void {
  }

}

// child.component.html

<p>输入的数据是:{{inputData}}</p>

<2>、第二种接收方式,方便于对数据进行切面拦截,inputData不能作为属性在模板中直接使用。

// child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.styl']
})

export class ChildComponent implements OnInit {

  public _inputData: string;

  constructor() { }

  ngOnInit(): void {
  }

  @Input() set inputData(data: string) {
    // 对从父组件传入的数据进行拦截处理
    const temp = data.toUpperCase();
    // _inputData可以作为属性在模板中使用
    this._inputData = temp;
  }

}

// child.component.html

<p>输入的数据是:{{_inputData}}</p>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值