Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Angular typescript - while enter key is pressed call an event in child directive

I have 3 nested components.

1st component.html I have used the selector of 2nd component and in 2nd component.html calling the 3rd component.

2nd component.html has an input box : <input type="text" (input)="val=$event.target.value" /> 3rd compont.html has the button. In 3rd component.ts - I have a onclick event, which will read the get the input box's value and redirect to new URL as :

@HostListener('click', ['$event']) onClick($event) {
    $event.preventDefault();
    window.location.href =`${this.URL}`;
}

I want to achieve the same while enter key is pressed after typing some text in the input box. Basically instead of button click after user types input while enter key is pressed, the onClick event in the 3rd component should fire. The problem is 3rd component has input variables from 1st and 2nd component which is used in URL formation. How to achieve this

Below are my components :

**1st component.html** 

<input-box [placeHolder]="'Type Here'" [searchType]="'A'"></input-box>


**2nd component : input-box.html**

<div class="box">
    <input type="text" (input)="searchValue=$event.target.value" placeholder={{placeHolder}} />
    <btn-icon [searchType]='searchType' [searchText]='searchValue'></btn-icon>
</div>

**3rd component - btn-icon.html**

<button id="btn1" class="btn" />

3rd component.ts :
export class btn-icon implements OnInit {
  
  @Input() searchType: string;
  @Input() searchText: string;
 
  ngOnInit(): void {
  }

@HostListener('click', ['$event']) onClick($event) {
    $event.preventDefault();
    window.location.href =`${this.URL}${this.searchText}`;
}
    
}

question from:https://stackoverflow.com/questions/65933247/angular-typescript-while-enter-key-is-pressed-call-an-event-in-child-directive

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...