我如何在Angular中使用ngModel捕获一个变量的值?



我只是想知道是否有某种方法可以将值传递给angular中的html文件中的变量。这里是我的代码

<div fxFlex="65" class="user-details" >
<div fxLayout="row" fxLayoutAlign="space-between center" >
<h4 class="user-name px-2">
{{ user.nombres }} {{ user.apellidos }}
</h4>
**<input matInput [(ngModel)]="name">**
<button mat-button color="primary" (click)="openDialog()">
<mat-icon>ballot</mat-icon>
</button>
</div>

我所需要的只是传递{{user的值。命名}}到变量"name"。这是因为在angular的typescript文件中,变量name正在等待这个值传递给接口,然后显示在对话框组件中。

这里是组件的默认typescript代码

import { DialogoPacienteComponent } from '../dialogo-paciente/dialogo- 
paciente.component';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from 
'@angular/material/dialog';
import { User } from '../users/user.model';
import { DataRowOutlet } from '@angular/cdk/table';
export interface DialogData {
name: string;
}
@Component({
selector: 'app-pacientes',
templateUrl: './pacientes.component.html',
styleUrls: ['./pacientes.component.scss'],
encapsulation: ViewEncapsulation.None,
providers: [PacienteService]
})
export class PacientesComponent implements OnInit {
name: string;
constructor(
public appSettings: AppSettings,
public router: Router,
public usersService: PacienteService,
private sanitizer: DomSanitizer,
paciente: Paciente,
public dialog: MatDialog
) {
this.settings = this.appSettings.settings;
}
ngOnInit() {
this.getUsers();
}
openDialog(): void {
let dialogRef = this.dialog.open(DialogoPacienteComponent, {
width: '250px',
data: {name: this.name},
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}

和我的代码在HTML中,我得到的值,我想传递给变量& name"在HTML中,立即将。或无所谓如果我能把它直接传递给name在。文件中,两者都是如果它能起作用,对我来说很好。

<div
*ngFor="
let user of users
<div fxFlex="65" class="user-details" >
<div fxLayout="row" fxLayoutAlign="space-between center" >
<h4 class="user-name px-2">
{{ user.nombres }} {{ user.apellidos }}
</h4>
<div>
**<!--here is where i need to catch the user.nombres value and 
assign it to variable name or pass it directly to ts.file-->
<input [(ngModel)]="name">**
</div>
<button mat-button color="primary" (click)="openDialog()">
<mat-icon>ballot</mat-icon>
</button>
</div>
</div>
</div

再一次提前感谢,

我假设user对象正在通过一个可观察对象、一个方法或诸如此类的对象进行更新。因此,我建议在更新user对象的同一位置简单地更新您的name变量。

所以我将简单地把这行放在组件的合适位置:

this.name = this.user.nombres;

并且由于[(ngModel)]是双向绑定,所以对this.name的更改也将显示在模板中。

根据目前的信息,我想这可以解决问题,除非我误解了问题。

最新更新