如何在primeNG菜单栏中执行Onclick事件

时间:2018-11-07 05:50:04

标签: angular primeng

如何使用PrimeNG执行点击事件。

单击“新建”菜单栏上的“添加新用户的UserFormComponent.html”页面。使用PrimeNG如何执行此操作。

我的代码位于:https://stackblitz.com/edit/angular-rlf3nz appcomponent.html

<p-menubar [model]="items">

appcomponent.ts

export class AppComponent {
  private user = new User();  //Newly added  
  constructor(private _userService:UserService) { }  //Newly added

  title = 'clientApp';
  private items: MenuItem[];

  ngOnInit() {
    this.items = [
    {
      label: 'Quotes',
      items: [
        { label: 'New ', icon: 'fa fa-refresh',  command: () => this.addNewUser()},
        { label: 'Show All', icon: 'fa fa-repeat', url: '#' }             
      ]
    }

   addNewUser(){
      this.user=this._userService.getter();
   } 

}

这是我的UserFormComponent.html

<div class="container">
  <form (ngSubmit)="processForm()">      
      <div class="form group">
        <label for="username">User Name</label>
        <input type="text" name="username" class="form-control" [(ngModel)]="user.username">
      </div>
      <div class="form group">
          <label for="type">Type</label>
          <input type="text" name="type" class="form-control" [(ngModel)]="user.type">
      </div>

      <div class="form group">
        <label for="modelname">Model Name</label>
        <input type="text" name="modelname" class="form-control" [(ngModel)]="user.modelname">
      </div> 
            <input type="submit" value="save" class="btn btn-success">
  </form>
</div>

这是我的UserFormComponent.ts

export class UserFormComponent implements OnInit {
  private user:User;
  constructor(private _userService:UserService,private _router:Router) {

   }

  ngOnInit() {
  this.user=this._userService.getter();
  }

  processForm(){
    if(this.user.id==undefined){
       this._userService.createUser(this.user).subscribe((user)=>{
         console.log(user);
         this._router.navigate(['/']);
       },(error)=>{
         console.log(error);
       });
    }else{
       this._userService.updateUser(this.user).subscribe((user)=>{
         console.log(user);
         this._router.navigate(['/']);
       },(error)=>{
         console.log(error);
       });
    }
  }

1 个答案:

答案 0 :(得分:1)

您可以使用command来调用函数。

ts

ngOnInit() {
    this.items = [
    {
      label: 'Quotes',
      items: [
        { label: 'New ', 
           icon: 'fa fa-refresh', 
           command: () => addNewUser(),
           //routerLink:"/demo"  <-- this can be moved inside the addNewUser function.
        },
        { label: 'Show All', icon: 'fa fa-repeat', url: '#' }             
      ]
    }

//Add new user
addNewUser(){
   this.user=this._userService.getter();
   this.user = new User()
}