How to pre-populate a post/edit template driven form

Discussão em 'Angular' iniciado por Zayno lane, Outubro 25, 2024.

  1. Zayno lane

    Zayno lane Guest

    All, I have a template-driven form that I use to post "blog posts" and the same form to edit the "blog posts." I have searched on Google and YouTube and found a tutorial that explains my attempts, but it's an older version of angular, and I get a lot of type string|null cannot be assigned to string errors

    My idea suggests assignment assertion operators, which remove the errors, but the forms do not populate. I read in Stackoverflow about the! operator, which also removes the errors, but still, I can't populate the form. What I expect is that whenever I click on the edit button, the same form I use for posting will populate with the database values (MongoDB).

    here are the codes:

    create post component

    post: Post | void | undefined;
    private mode = 'create';
    private postId: string | null | undefined;

    constructor(
    public postService: PostServiceService,
    public route: ActivatedRoute
    ) {}

    ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
    if (paramMap.has('postId')) {
    this.mode = 'edit';
    this.postId = paramMap.get('postId');
    this.post = this.postService.getPost(this.post);
    } else {
    this.mode = 'create';
    this.postId = null;
    }
    });
    }

    -------------------------------------------------------------------------------------------
    post service

    getPost(post?: void | Post | undefined) {
    //return [...this.posts];
    this.http
    .get<{ message: string; posts: any }>('http://localhost:4000/api/posts')
    .pipe(
    map((postData) => {
    return postData.posts.map((post: any) => {
    return {
    title: post.title,
    content: post.content,
    id: post._id,
    };
    });
    })
    )
    .subscribe((transformedtData) => {
    this.posts = transformedtData;
    this.postsUpdated.next([...this.posts]);
    });
    }

    -------------------------------------------------------------------------------------------
    app routing

    const routes: Routes = [
    { path: '', component: ListPostComponent },
    { path: 'create', component: CreatePostComponent },
    { path: 'edit/:postId', component: CreatePostComponent },
    ];

    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    })

    Continue reading...

Compartilhe esta Página