Angular 6 - 在父子组件之间共享变量
创始人
2024-10-16 03:00:14
0

在Angular 6中,可以使用Input和Output装饰器来在父子组件之间共享变量。

在父组件中,通过使用@Input装饰器来将变量传递给子组件。示例代码如下:

父组件的HTML模板:


父组件的TypeScript代码:

export class ParentComponent {
  parentValue: string = 'Hello from parent';

  constructor() { }
}

在子组件中,通过使用@Output装饰器来将变量传递回父组件。示例代码如下:

子组件的HTML模板:

{{childVariable}}

子组件的TypeScript代码:

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

export class ChildComponent {
  @Input() parentVariable: string;
  childVariable: string = 'Hello from child';

  @Output() parentVariableChange = new EventEmitter();

  constructor() { }

  updateParentVariable(): void {
    this.parentVariable = 'Updated value from child';
    this.parentVariableChange.emit(this.parentVariable);
  }
}

在父组件中,可以通过订阅子组件的事件来获取子组件传递回来的变量值。示例代码如下:

父组件的HTML模板:

{{parentValue}}

父组件的TypeScript代码:

export class ParentComponent {
  parentValue: string = 'Hello from parent';

  constructor() { }

  updateParentVariable(value: string): void {
    this.parentValue = value;
  }
}

在父组件的模块中,需要将子组件添加到declarations和exports数组中,以便能够在父组件中使用子组件。

这样,父子组件之间的变量共享就完成了。当子组件中的按钮被点击时,父组件的变量将被更新,并在父组件的模板中显示新的值。

相关内容

热门资讯

第9分钟辅助!wpk透视辅助靠... 第9分钟辅助!wpk透视辅助靠谱吗,wepoker透视脚本视频,机巧教程(有挂教学)wepoker透...
第十分钟辅助!werplan辅... 您好,wepoker游戏安装教程这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
一分钟辅助!哈糖大菠萝怎么开挂... 一分钟辅助!哈糖大菠萝怎么开挂,wepoker透视脚本免费,阶段教程(有挂规律)1、哈糖大菠萝怎么开...
第2分钟辅助!如何下载wepo... 第2分钟辅助!如何下载wepoker安装包,newpoker怎么安装脚本,模板教程(有挂秘诀)暗藏猫...
六分钟辅助!pokemmo辅助... 六分钟辅助!pokemmo辅助器,hhpoker作弊实战视频,窍门教程(有挂实锤)1、下载好hhpo...
7分钟辅助!wepoker有辅... 7分钟辅助!wepoker有辅助器吗,拱趴大菠萝万能辅助器,诀窍教程(存在有挂)1、点击下载安装,拱...
第八分钟辅助!hhpoker哪... 第八分钟辅助!hhpoker哪个俱乐部靠谱,约局吧作弊脚本,法子教程(有挂助手)运hhpoker哪个...
三分钟辅助!约局吧怎么看有没有... 三分钟辅助!约局吧怎么看有没有挂,wpk辅助器是真的吗,技法教程(有人有挂)1、约局吧怎么看有没有挂...
9分钟辅助!菠萝辅助器免费版的... 9分钟辅助!菠萝辅助器免费版的功能介绍,hhpkoer辅助器,手段教程(有挂秘籍)1、菠萝辅助器免费...
第七分钟辅助!拱趴大菠萝有什么... 第七分钟辅助!拱趴大菠萝有什么挂,wepoker辅助工具,法子教程(有挂技巧)1、不需要AI权限,帮...