angular如何实现创建功能和修改功能在同一个组件中
刚刚接触angular,创建功能和修改功能可以公用一个组件。记录如下
html:
<form nz-form #validateForm="ngForm" (ngSubmit)="submitForm()" nzLayout="horizontal" autocomplete="off">
<!-- 模态框头部 -->
<div class="modal-header">
<div class="modal-title">
<i class="anticon anticon-medicine-box mr-sm"></i>
<span *ngIf="entity.id">{{l('Edit')}}</span>
<span *ngIf="!entity.id">{{l('Create')}}</span>
</div>
</div>
<!-- 模态框内容 -->
<fieldset>
<fieldset>
<!-- 模态框底部 -->
<div class="modal-footer">
<button nz-button [nzType]="'default'" type="button" (click)="close()" [disabled]="saving">
<i class="anticon anticon-close-circle-o"></i> {{l("Cancel")}}
</button>
<button nz-button [nzType]="'primary'" type="submit" [disabled]="!validateForm.form.valid|| saving" [nzLoading]="saving">
<i class="anticon anticon-save" *ngIf="!saving"></i> {{l("Save")}}
</button>
</div>
</form>
ts文件
需要引入的相关内容都和正常的写法一样都需要引入好。例如 相对应的类 相对应的http的请求
要注意的是在初始化的时候要判断是否初始化值进去
this.tenantService.getAuthorizationByTenantId( this.tenantId ).subscribe(data => {
this.entity = data;
})
save(): void {
this.entity.normalFormIds = normalFormCheckKeys; //这是要提交给后台的值
this.entity.scaleIds = scaleCheckKeys
this.saving = true;
//下面的是接口提交给后台的接口服务
this.tenantService.authorizationNormalFormAndScale(this.entity)
.finally(() => {
this.saving = false;
})
.subscribe(() => {
this.notify.success(this.l('SavedSuccessfully'));
this.success();
});
注意:
在constructor的函数里需要注入需要的服务
constructor(
private tenantService: TenantServiceProxy) {
}
在service.proxies.ts中拥有请求数据的方法
authorizationNormalFormAndScale(tenantAuthorization: TenantAuthorizationDto | null | undefined): Observable<void> {
let url_ = this.baseUrl + "/api/services/app/Tenant/AuthorizationNormalFormAndScale";
url_ = url_.replace(/[?&]$/, "");
...
}
这样就完成了一个页面实现两个功能