Angular:将数据从组件发送到另一个组件

标签 angular typescript

我正在学习 Angular,我有这些组件:

MainComponent.ts

import {Component} from 'angular2/core';
import {UsersTableComponent} from './UsersTableComponent';
import {UserAddComponent} from './UserAddComponent';

@Component({
    selector: 'main',
    templateUrl: '../app/views/mainView.html',
    directives: [UsersTableComponent, UserAddComponent]
})

export class MainComponent {
    constructor() {}
}

UserAddComponent.ts

import {Component} from 'angular2/core';
import {GenderPipe} from '../pipes/GenderPipe';

@Component({
    selector: 'userAdd',
    templateUrl: '../app/views/userAdd.html',
    pipes: [GenderPipe]
})

export class UserAddComponent {
    constructor() {}

    addUser() {
        alert(1);
    }
}

用户表组件

import {Component} from 'angular2/core';
import {UserServices} from '../services/UserServices';
import {User} from '../classes/User';
import {GenderPipe} from '../pipes/GenderPipe';

@Component({
    selector: 'usersTable',
    templateUrl: '../app/views/usersTable.html',
    pipes: [GenderPipe]
})

export class UsersTableComponent {
    users: Array<User>

    constructor(UserServices: UserServices) {
        this.users = UserServices.getUsers();
    }
}

在 addUser 方法的 UserAddComponent 上,我需要从模板中读取一些值并通过 UserServices 更新用户。更新时,我需要从 UserTableComponent 调用一个方法,以便刷新包含添加到用户的数据的表。

如何从一个组件中调用另一个组件中的方法?

最佳答案

让两个组件的父组件在属性中保存用户列表,并使用@Input将其传递给两个子组件,这样只要列表出现,两个组件都会使用react变化:

https://angular.io/docs/ts/latest/api/core/Input-var.html

您也可以使用 @Output 引发事件:

https://angular.io/docs/ts/latest/api/core/Output-var.html

关于Angular:将数据从组件发送到另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880261/

相关文章:

javascript - awesome-typescript-loader 无法加载 ts 文件

Angular 6 : calculating the sum of a list (Observable)

Angular 6 - 为什么生产版本中缺少 Bearer Token? (在开发构建中工作正常)

javascript - 从 typescript 库导入的符号未定义

javascript - 如何使用 Angular Material 在具有可扩展行的表中创建嵌套垫表

javascript - Angular4 typescript ;类型 'data' 上不存在属性 'any[]'

unit-testing - 如何设置 karma/jasmine 与 ionic2 一起工作?

android - 找不到:couchbase-lite-android-1.4.1-Ionic Android

javascript - 从事件中获取 vue 组件

javascript - 数组的 ES5 与 ES6 Javascript