gpt4 book ai didi

Angular 2 从 2 个几乎相同的组件中制作一个 "generic"组件

转载 作者:太空狗 更新时间:2023-10-29 17:57:58 24 4
gpt4 key购买 nike

我有 2 个几乎相同的组件,为了代码的可重用性,我想将它们组合起来以在我的项目的不同地方使用。两者都是带有复选框的下拉列表。唯一的区别是传入和传出的数据。

import {ROUTER_DIRECTIVES, RouteConfig, RouteParams, Router, RouterOutlet, RouterLink} from 'angular2/router';
import {FORM_PROVIDERS, FORM_DIRECTIVES, Control, NgClass, NgIf, CORE_DIRECTIVES} from 'angular2/common';
import {Component, Inject, Input, OnInit, OnChanges} from 'angular2/core';
import {Http, Headers, ContentHeaders, HTTP_PROVIDERS} from 'angular2/http';
import {User} from '/app/interfaces';
import {ActualsComponent } from '../actuals/actual.component';
import {ProjectService} from '../../projects/project.service';
import {LoginService} from '../../login/login.service';
import {SearchPipe} from '../custom-pipes/search-pipe';

@Component({
selector: 'dropdown-users',
templateUrl: 'app/templates/elements/dropdown-users.html',
providers: [FORM_PROVIDERS, HTTP_PROVIDERS, ProjectService, LoginService],
directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES, RouterLink, CORE_DIRECTIVES, RouterOutlet],
pipes: [SearchPipe]
})

export class DropDownUsers implements OnInit, OnChanges{
projectdata: Object;
selectedUsers: Object;

public showMenu: boolean;
projectSearchTerm: Control = new Control();
projectcount: number;

constructor(@Inject(ProjectService) projectService: ProjectService, @Inject(LoginService) loginService: LoginService, private http: Http, params: RouteParams) {
this.showMenu = false;
loginService.authenticate("user", "pwd");
this.projectdata = loginService.data;
this.projectcount = 0;
this.selectedUsers = new Array();

}
addUser(user: User){
this.selectedUsers.push(user);
}
}

其他组件是相同的,除了它与用户而不是项目一起工作。

最佳答案

你可以创建一个具有通用功能的基类,当你想继承通用的东西,或者改变/覆盖特定的东西时扩展它。

class Base {
selected: any[];
constructor(DI_ARGS) {
this.selected = [];
}
add(o) { this.selected.push(o); }
}

@Component({ template: `
<button (click)="add('Mike')">Add User</button>
<p>selected users: <a *ngFor="#user of selected">{{ user }}, </a></p>
` })
class Users extends Base {
constructor(DI_ARGS) {
super(DI_ARGS);
}
}

@Component({ template: `
<button (click)="add('build house')">Add Project</button>
<p>selected projects: <a *ngFor="#project of selected">{{ project }}, </a></p>
` })
class Project extends Base {
constructor(DI_ARGS) {
super(DI_ARGS);
}
}

有一些注意事项:

  • 不能在基类中使用装饰器
  • 要使用依赖注入(inject),您必须通过 super() 提供构造函数参数
  • 您可以(默认情况下)只扩展一个类

关于Angular 2 从 2 个几乎相同的组件中制作一个 "generic"组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35621688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com