Angular 11中点击文本后如何使用setValue将数据传入另一个组件的输入文本框
setValue Got it, let's get this working step by step. Right now, you're navigating to Component2 but not sending the selected tag details along—so Component2 has no way to know what text to put in the input. Here are two reliable ways to fix this using Angular 11's setValue method:
Option 1: Pass Data via Route Query Params (Simple, URL-Visible)
This is great for straightforward text data that you don't mind showing in the URL.
Step 1: Update Component1 to Pass the Tag Details in the Route
Modify your tagname function to include the tag text as a query parameter when navigating:
// Component1.ts import { Router } from '@angular/router'; // ... tagname(element){ const tagDetails = `${element.tagName} ${element.description}`; console.log("-----------DETAILS-----------", tagDetails); // Navigate to Component2 and pass the tag details as a query param this.router.navigate(['/component2'], { queryParams: { tag: tagDetails } }); // Keep your emit if you need to notify a parent component, but it's not required for this flow // this.clickEvent.emit(tagDetails); }
Step 2: Update Component2 to Fetch the Param and Set the Input Value
In Component2, use ActivatedRoute to grab the query parameter, then use setValue to populate the form control:
// Component2.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-component2', templateUrl: './component2.html', styleUrls: ['./component2.css'] }) export class Component2 implements OnInit { myControl = new FormControl(''); filteredOptions: any; // Keep your existing filteredOptions logic here constructor(private route: ActivatedRoute) { } ngOnInit(): void { // Subscribe to query params to get the tag text this.route.queryParams.subscribe(params => { const tagText = params['tag']; if (tagText) { // Use setValue to update the input field this.myControl.setValue(tagText); // Optional: Trigger your filter logic here if needed // this.filteredOptions = ... (match your existing auto-complete filtering) } }); } // Keep your existing getPosts method getPosts(value: any) { // ... your existing code } }
Option 2: Pass Data via a Shared Service (URL-Invisible, Good for Complex Data)
If you don't want the tag text showing up in the URL, use a shared service with a BehaviorSubject to pass data between components.
Step 1: Create a Shared Data Service
// data-share.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataShareService { private tagSubject = new BehaviorSubject<string>(''); currentTag = this.tagSubject.asObservable(); constructor() { } setTag(tag: string) { this.tagSubject.next(tag); } }
Step 2: Update Component1 to Send Data via the Service
// Component1.ts import { Router } from '@angular/router'; import { DataShareService } from '../services/data-share.service'; // Adjust path as needed // ... constructor(private router: Router, private dataShareService: DataShareService) { } tagname(element){ const tagDetails = `${element.tagName} ${element.description}`; console.log("-----------DETAILS-----------", tagDetails); // Send the tag text to the service this.dataShareService.setTag(tagDetails); this.router.navigateByUrl("/component2"); }
Step 3: Update Component2 to Receive Data and Set the Input
// Component2.ts import { Component, OnInit } from '@angular/core'; import { DataShareService } from '../services/data-share.service'; // Adjust path as needed import { FormControl } from '@angular/forms'; @Component({ selector: 'app-component2', templateUrl: './component2.html', styleUrls: ['./component2.css'] }) export class Component2 implements OnInit { myControl = new FormControl(''); filteredOptions: any; // Keep your existing filteredOptions logic constructor(private dataShareService: DataShareService) { } ngOnInit(): void { // Subscribe to the service to get the tag text this.dataShareService.currentTag.subscribe(tagText => { if (tagText) { this.myControl.setValue(tagText); } }); } // Keep your existing getPosts method getPosts(value: any) { // ... your existing code } }
Both methods will work, but pick the one that fits your use case:
- Use query params if you want the tag text to be bookmarkable or visible to users.
- Use a shared service if you need to pass more complex data or want to keep the URL clean.
内容的提问来源于stack exchange,提问作者bilu sau

