将component.html的插值值调用到component.ts

时间:2018-06-07 17:17:48

标签: angular

我是Angular的新手,我有一个材料表,我有这样的字段:

<mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.id}} 
</mat-cell>

<mat-cell *matCellDef="let user">
      <switch [status]="user.activo" [onText]="yes" [offText]="no" [onColor]="green" [offColor]="gray" [size]="normal" [disabled]="disabled" (statusChange)="onFlagChange($event)"></switch>
 </mat-cell>

正如你所看到的,我在这里有2个细胞。最后一个是使用事件的Bootstrap switch

(statusChange)="onFlagChange($event)

所以/我创建一个服务来改变当前用户的状态,如:

postSwitch(body) {
var cambioEstatus = this.http
  .put(
    this.rootUrl + "api/usuarios/activar",
    JSON.stringify(body),
    this.options
  )
  .map((data: any) => data.json());
return cambioEstatus;
 }

和我用来填充表的方法是:

 getUser(): Observable<User[]> {
    return this.httpClient.get<User[]>(this.serviceUrl, {
      headers: this.headersNew
    });
  }

然后在component.ts中我只调用方法:

onFlagChange(event) {
    const body: any = {
      usuarioId: ,
      activo: event
    };
    this.UsuariosService.postSwitch(body).subscribe(
      () => {
        //React to your HTTP request success
        this.toastr.success("Changed success");
      },
      err => {
        this.toastr.error("Error");
        //React to your HTTP request error
      }
    );
   }

你可以看到我有

const body: any = {
      usuarioId: ,
      activo: event
    };

但我不知道如何从视图中获取{{user.id}}。我怎样才能做到这一点?此致

完整的component.ts:

import {
  Component,
  Input,
  OnInit,
  ViewEncapsulation,
  ViewChild,
  ElementRef
} from "@angular/core";
import { ModalDismissReasons, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
import { ScriptLoaderService } from "../../../../../_services/script-loader.service";
import { ToastrService } from "ngx-toastr";

import { UsuariosService } from "../../../../../_services/usuarios.service";
import { Observable } from "rxjs/Observable";
import {
  DataSource,
  CollectionViewer,
  SelectionModel
} from "@angular/cdk/collections";
// import { User } from "../../../../../_models/user.model";5
import { BehaviorSubject } from "rxjs";
import {
  MatSort,
  MatSortable,
  MatTableDataSource,
  MatPaginator,
  MatPaginatorIntl
} from "@angular/material";
import { UsuarioActivo } from "../../../../../_models/usuarioActivo";


@Component({
  selector: "usuarios",
  templateUrl: "./usuarios.component.html",
  encapsulation: ViewEncapsulation.None
})
export class UsuariosComponent {
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild("filter") filter: ElementRef;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  // Bootstrap switch
  public yes: string = "SI";
  public no: string = "NO";
  public green: string = "green";
  public gray: string = "gray";
  public disabled: boolean = false;
  public status: boolean = false;
  public normal: string = "small";
  //end Bootstrap switch

  selection = new SelectionModel<string>(true, []);
  dataSource;

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  displayedColumns = [
    "id",
    "nombre",
    "apellido",
    "email",
    "perfil",
    "ultimoLogin",
    "activo",
    "action"
  ];

  constructor(
    private _script: ScriptLoaderService,
    private toastr: ToastrService,
    private UsuariosService: UsuariosService
  ) {}

  ngOnInit() {
    this.UsuariosService.getUser().subscribe(results => {
      if (!results) {
        return;
      }
      this.dataSource = new MatTableDataSource(results);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;

    });


  }

  onFlagChange(event, userid) {
    const body: any = {
      usuarioId: userid,
      activo: event
    };
    this.UsuariosService.postSwitch(body).subscribe(
      () => {
        //React to your HTTP request success
        this.toastr.success("Cambiado con éxito");
      },
      err => {
        this.toastr.error("Falló");
        //React to your HTTP request error
      }
    );
  }

}

1 个答案:

答案 0 :(得分:1)

请记住,您的模板上下文中包含user

<mat-cell *matCellDef="let user"> <switch [status]="user.activo" [onText]="yes" [offText]="no" [onColor]="green" [offColor]="gray" [size]="normal" [disabled]="disabled" (statusChange)="onFlagChange($event, user)"></switch> </mat-cell>

在这种情况下,您可以向onFlagChange()功能添加第二个参数并接收当前用户。