Angular 2中如何验证用户点击提交按钮(输入文本后需点击再跳转)
Absolutely! You can handle this "must-click-button-before-navigation" requirement entirely within your current component—no need to pass a boolean to a separate navigation component. Here's a straightforward approach tailored to your code:
Step 1: Add a tracking variable in your component class
First, declare a boolean property to keep track of whether the submit button has been clicked:
export class YourComponent { searchValue: string = ''; isSearchButtonClicked = false; // Tracks if the button was clicked // Your existing func() method func() { // Reset click status if user edits input after clicking this.isSearchButtonClicked = false; // ... rest of your existing logic here } // New handler for button clicks onSearchButtonClick() { this.func(); // Keep your original button logic this.isSearchButtonClicked = true; // Mark button as clicked } // Your navigation method (adjust to match your actual flow) navigateToNextPage() { // Validate both input presence and button click if (!this.searchValue || !this.isSearchButtonClicked) { alert('Please enter a domain and click the search button before moving to the next page!'); return; // Block navigation if validation fails } // Proceed with your normal navigation logic here // Example: this.router.navigate(['/next-page']); } }
Step 2: Update your template
Modify the button to use the new click handler, and keep your input as-is (the ngModelChange will reset the click status whenever the user edits their input):
<input type="text" class="form-control ng-pristine ng-valid ng-touched" placeholder="Search for a domain" name="page1.domainSearch" [(ngModel)]="searchValue" (ngModelChange)="func()" /> <button type="submit" class="search" (click)="onSearchButtonClick()" [disabled]="!searchValue" ></button>
How this works:
- When the user types in the input,
ngModelChangetriggersfunc(), which resetsisSearchButtonClickedtofalse—this ensures that if the user edits their input after clicking the button, they have to click it again to confirm the new value. - When the user clicks the enabled button,
onSearchButtonClick()runs your existing logic and marks the button as clicked. - When attempting to navigate to the next page,
navigateToNextPage()checks both that the input has a value and that the button was clicked. If either condition fails, navigation is blocked and the user gets a clear prompt.
This keeps all validation logic self-contained in your component, no external component communication required.
内容的提问来源于stack exchange,提问作者Shashank
相关产品推荐
相关产品推荐

