如何阻止Angular在(click)事件后重置文本域值及处理PDF提取JSON
Hey there, let's tackle your two questions one by one:
This issue usually stems from a few common causes, each with straightforward fixes:
- Button triggers default form submission: If your button is wrapped in a
<form>tag, Angular buttons default totype="submit". Clicking it will trigger a form submission, which refreshes the page and resets your text area. Fix this by explicitly setting the button'stypetobutton:
<form> <textarea [(ngModel)]="content"></textarea> <!-- Add type="button" to block default submission --> <button type="button" (click)="handleClick()">Execute Action</button> </form>
Accidental value reset in click logic: Check your component's
.tsfile for the click handler function. If your text area is bound to a variable likecontent, make sure the function doesn't have code likethis.content = ''that resets the value unintentionally—just remove those lines.Event bubbling/default behavior interference: If neither of the above applies, pass
$eventto your click handler and manually block default behavior and bubbling:
<textarea [(ngModel)]="content"></textarea> <button (click)="handleClick($event)">Execute Action</button>
Component code:
handleClick(event: Event) { // Prevent default browser behavior event.preventDefault(); // Stop the event from bubbling to parent elements event.stopPropagation(); // Your business logic here... }
The text field in your JSON snippet contains escaped newline characters (\n). To get these to display properly as line breaks, use these approaches based on your use case:
- Displaying in a Text Area: Just use two-way binding
[(ngModel)]to bind to thetextfield—text areas automatically recognize\nand render them as line breaks:
<textarea [(ngModel)]="serviceText" rows="12" cols="70"></textarea>
Component code (assuming you've already fetched and parsed the JSON from your server):
// Simulate the raw JSON data from your server const rawData = { "ServiceOfSuit": { "text": "本保险受华盛顿州修订法典(RCW)管辖并依其解释。各方同意接受美国境内任何有管辖权法院的专属管辖。\n\nNMA 1998(1986年4月24日)诉讼送达条款:A.N.O.律师事务所(或其指定人) 主街211号\n\n奥林匹亚\n\n华盛顿州(WA)..." } }; this.serviceText = rawData.ServiceOfSuit.text;
- Displaying in a regular HTML element (e.g., div): Add the CSS property
white-space: pre-line(merges consecutive whitespace but preserves line breaks) orwhite-space: pre(preserves all whitespace and line breaks) to the element so the browser parses\ncorrectly:
<div class="pdf-text">{{ serviceText }}</div>
Corresponding CSS:
.pdf-text { white-space: pre-line; /* Use white-space: pre; if you need to keep original indentation/spacing */ padding: 10px; border: 1px solid #eee; }
Note: If your server returns the JSON as a string, remember to parse it into a JavaScript object first with JSON.parse() before accessing the text field.
内容的提问来源于stack exchange,提问作者Jahangir

