我可能一周有这个问题,我有一个使用菜单和子菜单的代码。
我有一个包含名称和子菜单的菜单,以及包含名称的子菜单。
我的menu.component.ts
import { Component, OnInit, ViewChild, ElementRef, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { ActivatedRoute, Router } from '@angular/router'
declare var $: any;
import { Menu_Service } from '../menu.service';
import { MenuInterface } from '../menu.interface';
import { PagetitleService } from '../../../core/pagetitle/pagetitle.service';
var swal = require('sweetalert');
@Component({
// moduleId:module.id,
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MenuComponent implements OnInit {
public data = {};
public myForm: FormGroup;
public route: ActivatedRoute;
public router: Router;
public http: Http;
public headers: Headers;
public mensagem: string = '';
public service: Menu_Service;
constructor(private _fb: FormBuilder, pt: PagetitleService, route: ActivatedRoute, router: Router, http: Http, service: Menu_Service) {
pt.setTitle('');
this.service = service;
this.route = route;
this.router = router
this._load();
}
private _load() {
}
ErrorMessage(error) {
swal('Oops...', error, 'error');
}
//I create here my form group here
ngOnInit() {
this.myForm = this._fb.group({
role: ['', [Validators.required, Validators.minLength(5)]],
menus: this._fb.array([this.initMenu()]),
});
this.route.params.subscribe(params => {
let id = params['id'];
if (id) {
this.service
.searchId(id)
.subscribe(data => {
this.data = data.data[0]
const subcontrol = <FormArray>this.myForm.controls['submenus'];
const control = <FormArray>this.myForm.controls['menus'];
for (var i in this.data.menus) {
const nameCtrl = this.loadMenu(this.data.menus[i].name);
control.push(nameCtrl);
}
}, erro => console.log(erro))
}
else{
this.addMenu();
};
});
// add address
}
initMenu() {
return this._fb.group({
name: ['', Validators.required],
submenu: this._fb.array([this.initSubMenu()]),
});
}
initSubMenu() {
return this._fb.group({
name: ['', Validators.required]
});
}
loadMenu(value: String) {
return this._fb.group({
name: [value, Validators.required]
});
}
loadSubMenu(value: String) {
return this._fb.group({
name: [value, Validators.required]
});
}
addMenu() {
const control = <FormArray>this.myForm.controls['menus'];
const menuCtrl = this.initMenu();
control.push(menuCtrl);
/* subscribe to individual address value changes */
// addrCtrl.valueChanges.subscribe(x => {
// console.log(x);
// })
}
removeMenu(i: number) {
const control = <FormArray>this.myForm.controls['menus'];
control.removeAt(i);
}
removeSubMenu(i: number) {
const control = <FormArray>this.myForm.controls['submenus'];
control.removeAt(i);
}
save(event:MenuInterface) {
// event.preventDefault();
this.data.role = event.value.role;
this.data.menus=event.value.menus;
// this.data.submenus=event.values.submenus;
this.service
.cadastra(this.data)
.subscribe(res => {
if (res.success) {
swal({
title: 'Good job!',
text: 'You clicked the button!',
type: 'success'
}, ()=>{
this.router.navigate(['/admin/menus/list'])
});
}
else {
this.ErrorMessage("Server off-line")
}
}, erro => console.log(erro));
}
}
我的menu.component.html
<div class="container-fluid">
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
<div class="card">
<div class="card-body">
<label class="mt">Role</label>
<input type="text" formControlName="role" [(ngModel)]="data.role" class="form-control">
<small *ngIf="!myForm.controls.role.valid" class="text-danger help-block">Role is required (minimum 5 characters).</small>
</div>
<div class="card-body">
<div class="panel panel-default">
<div class="panel-heading">Menus for this Role: </div>
<div class="panel-body">
<!--
<div *ngFor="let menu of myForm.controls.menus.controls; let i=index">
<div class="row" formArrayName="menus">
<div class="col-md-12" [formGroupName]="i">
Tste: {{myForm.controls.menus.controls.length}}
<input type="text" placeholder="Enter your menu title here{{i}}" class="form-control" formControlName="name" />
<small class="text-danger" [hidden]="myForm.controls.menus.controls[i].controls.name.valid">* name is required </small>
<small type="button" style="cursor: default" *ngIf="myForm.controls.menus.controls.length > 1" (click)="removeMenu(i)" class="text-danger pull-right"><span class="ion-trash-a"></span> delete</small>
</div>
</div>
</div>
-->
<div formArrayName="menus">
<div *ngFor="let menus of myForm.controls.menus.controls; let i=index">
<!-- address header, show remove button when more than one address available -->
<div>
<span>menus {{i + 1}}</span>
<span *ngIf="myForm.controls.menus.controls.length > 1"
(click)="removeMenus(i)">
</span>
</div>
<!-- Angular assigns array index as group name by default 0, 1, 2, ... -->
<div [formGroupName]="i">
<!--street-->
<div>
<label>Name</label>
<input type="text" formControlName="name">
<!--display error message if street is not valid-->
<small [hidden]="myForm.controls.menus.controls[i].controls.name.valid">
Name is required
</small>
</div>
<!--postcode-->
<div>
<label>SubMenu</label>
<div *ngFor="let submenus of myForm.controls.menus.controls[i].controls.submenus; let ii=index">
<div [formGroupName]="ii">
<input type="text" formControlName="name">
</div>
</div>
</div>
<div>
</div>
</div>
</div>
<div class="panel-body">
<div class="col-md-12 text-left">
<a (click)="addMenu()" style="cursor: default"><span class="ion-ios-plus"></span> Add another menu</a>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-body text-center">
<button type="submit" [disabled]="!myForm.valid" class="btn btn-primary ripple">Save</button>
</div>
</div>
</form>
</div>