Angular-当点击编辑按钮时,如何使用先前的数据加载创建表单(另一个组件)并添加更新按钮?我该怎么做?
创始人
2024-10-21 03:31:17
0
  1. 创建一个名为“edit-component”的组件,用于显示和编辑数据。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DataService } from '../data.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-edit-component',
  templateUrl: './edit.component.html',
})
export class EditComponent implements OnInit {

  id: number;
  dataForm: FormGroup;

  constructor(private route: ActivatedRoute, private router: Router, private dataService: DataService) { }

  ngOnInit() {
    this.dataForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'phone': new FormControl(null, Validators.required)
    });

    this.route.params.subscribe(params => {
      this.id = +params['id'];
      const data = this.dataService.getDataById(this.id);
      this.dataForm.setValue({
        'name': data.name,
        'email': data.email,
        'phone': data.phone
      });
    });
  }

  onSubmit() {
    this.dataService.updateData(this.id, this.dataForm.value);
    this.router.navigate(['/list-component']);
  }

}
  1. 创建一个名为“list-component”的组件,用于显示数据及编辑和删除数据。
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-component',
  templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {

  data: any[];

  constructor(private dataService: DataService, private router: Router) { }

  ngOnInit() {
    this.data = this.dataService.getData();
  }

  onEdit(id: number) {
    this.router.navigate(['/edit-component', id]);
  }

  onDelete(id: number) {
    this.dataService.deleteData(id);
    this.ngOnInit();
  }

}
  1. 在“list-component”的HTML文件中添加以下内容,以显示每条数据,并在每

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...