gpt4 book ai didi

Angular 5 - 如何在初始化后重新加载组件

转载 作者:太空狗 更新时间:2023-10-29 17:36:44 25 4
gpt4 key购买 nike

我在应用程序中有一个搜索功能。当用户单击搜索按钮时,数据将在 [(ngModel)] 中捕获并传递给服务。 URL 被重定向到 SearchComponent 的 HTML。此服务被注入(inject)到 SearchComponent 中并显示数据。

当用户输入新的搜索词时,我想刷新现有的 SearchComponent。执行此操作的正确方法是什么?

搜索.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';

@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

userInput : string;
constructor(private data : DataService) { }

ngOnInit(){
this.search();
}

search(){

this.userInput = this.data.searchData;
console.log('in search init ' + this.userInput);
this.data.searchData = "";
}
}

应用程序组件.ts

import { Component } from '@angular/core';
import { DataService } from './service/data.service';


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private data : DataService){};

title = 'app';
searchInput: string;

searchButtonclick(){
console.log('search button clicked ' + (this.searchInput));
this.data.searchData = this.searchInput
this.searchInput = "";
}

}

app.component.html

<form>
<input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield">
<a routerLink="/search">
<button (click)="searchButtonclick()">Search</button>
</a>
</form>

最佳答案

我建议使用 search.component.ts 作为子组件并使用 @Input :

app.component.html

<form>
<input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield">
<app-search [userInput]="searchInput"></app-search>
</form>

search.component.ts

@Input() userInput: string;

ngOnChange(){
// this will be called each time userInput changes
this.search();
}

参见 this article了解更多信息


如果你想要在点击事件时,你只需要一个额外的变量,比如 searchvalue

app.component.html

<form>
<input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield">
<button (click)="searchButtonclick()">Search</button>
<app-search [userInput]="searchvalue"></app-search>
</form>

app.component.ts

searchvalue:string;
searchButtonclick(){
this.searchvalue = this.searchInput;
}

search.component.ts

// as above

关于Angular 5 - 如何在初始化后重新加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com